integ/iri/js/iri-buzz.js
changeset 54 faf1e584551c
parent 53 88666afffe6b
child 55 c2e76eb7be88
--- a/integ/iri/js/iri-buzz.js	Mon Apr 29 15:02:35 2013 +0200
+++ b/integ/iri/js/iri-buzz.js	Mon Apr 29 18:37:06 2013 +0200
@@ -1,409 +1,258 @@
-$(function(){
-
-/*
-$(window).bind('resize', function(){
-	setSidebarContentHeight();
-});
-setSidebarContentHeight();
-function setSidebarContentHeight(){
-	var newHeight = $(window).height() - $('header').height() - $('footer').height();
-	$(".sidebar .content").css('height', newHeight);
-}
+var SECONDS = 1000,
+    MINUTES = 60 * SECONDS,
+    HOURS = 60 * MINUTES;
 
-*/
-
-
-
-var CONFIG = {
-	wChart : 150,
-	hVS : 200,
-	now : new Date(),
-	dayLimit : 1,
-	timelineMin : 5,
-	bar : [],
+var config = {
+    partnerCode: 'B00015838755',
+    originalDuration: 24 * HOURS,
+    vizDuration: 10 * MINUTES,
     colorIds: {
         "-2.0": 2,
         "0.5": 0, "1.0": 0, "1.5": 0, "2.0": 0,
         "2.5": 1, "3.0": 1, "3.5": 1,
         "4.0": 2, "4.5": 2, "5.0": 2
     },
-    colors: [ "#c00000", "#ffd000", "#008000"]
-};
-
-function init(){
-	var wWin = ($(window).width()>520) ? $(window).width() : 520;
-	$('.timer-bar').width(wWin - 170);
-
-	var stepHour = CONFIG.dayLimit * 24 / 12;
-	var hourText = 0;
-	$('.hours li').each(function(k, v){
-		$(v).text(hourText+'h');
-		hourText = hourText + stepHour;
-	});
-
-	var wTimerBar = $('.timer-bar').width(),
-		nbIndicator = $('.hours li').length-1;
-		mrIndicator = wTimerBar/ (nbIndicator);
-	$('.timeline-head').css('min-width', wWin);
-	$('.hours li').each(function(k,v){
-		if(k >= nbIndicator - 1) return;
-		var mr = mrIndicator  - $('.hours li:last-child').width()/2 - $(v).width()/2;
-		$(v).css('margin-right', mr);
-	});
-
-
-	var spaceTop = 100, spaceBotPoster = 200;
-	CONFIG.hVS = $(window).height() - $('footer').height() - $('header').height() - spaceTop - spaceBotPoster;
-	CONFIG.hVS = (CONFIG.hVS>200) ? CONFIG.hVS : 200;
-
-	showHorloge();
-}
-
-init();
-
-
-var bcSettings = {
-	width : 960,
-	height : CONFIG.hVS,
-	chart : {
-		spacer : 5,
-		y: 150,
-		height: CONFIG.hVS - 150
-	},
-	data : {
-		model :[],
-		strata:[],
-		stream : { provider : 'direct' }
-	},
-	sedimentation:{
-	    token:{
-	      size:{original:12,minimum:0}
-	    },
-	    aggregation:{
-	        height: CONFIG.hVS - 150,
-	        maxData: 50
-        },
-	    suspension:{
-	      decay:{power:1.001}
-	    }
-  	},
-  	options:{layout:false}
-};
-
-var currentDay = new Date().getDate();
-var _reviewMovies = [];
-var nbMovies;
-var indiceMovie = 0;
-var indiceBar = 0;
-var barChart;
-var count = 10;
-var urlBestMovies = 'http://api.allocine.fr/rest/v3/movielist?partner='+ partnerCode +'&format=json&filter=top:week&count='+count;
-$.getJSON(urlBestMovies, function(data) {
-	
-	var movies = data.feed.movie;
-	nbMovies = movies.length;
-	bcSettings.width = nbMovies * CONFIG.wChart + (10 * nbMovies);
-	$('.posters').css('width', bcSettings.width);
-	//var wItem = bcSettings.width / nbMovies;
-
-	_.each(movies, function(d, i){
-
-		var dataMovie = {
-			title : d.originalTitle,
-			code : d.code,
-			posterUrl : d.poster.href,
-			userRating : d.statistics.userRating,
-			userReviewCount : d.statistics.userReviewCount
-		};
-
-		var poster = 
-			'<li>'+
-				'<img width="150" height="200" src="'+ dataMovie.posterUrl  +'" alt="'+ dataMovie.title +'" />'+
-			'</li>';
-		$('.posters').append(poster);
-
-		getReviewsByFilm(dataMovie.code);
-
-		CONFIG.bar.push(dataMovie.code);
-
-		bcSettings.data.model.push({label:"Column A"});
-
-
-	});
-
-	console.log(CONFIG.bar);
-	
-	bcSettings.data.strata = function() {
-	    if (typeof barChart === "undefined") {
-	        var flocculated = [];
-	        _(function() {
-	            _.range(3).map(function(colorId) {
-	                $(".layer_"+colorId).css("fill", CONFIG.colors[colorId]);
-	            });
-	        }).defer();
-	    } else {
-	        var flocculated = barChart.selectAll("state",2);
-	    }
-	    
-	    var res = CONFIG.bar.map(function(movieCode) {
-	        var movieTokens = flocculated.filter(function(t) {
-	            return t.attr("movieCode") === movieCode;
-	        });
-	        return _.range(3).map(function(colorId) {
-	            var stratumTokens = movieTokens.filter(function(t) {
-    	            return t.attr("colorId") === colorId;
-    	        }).length;
-	            return {
-	                value: function() {
-	                    return stratumTokens
-	                },
-	                text: stratumTokens
-	            }
-	        });
-	    });
-	    return res;
-	};
-	
-	barChart = $("#data-viz").vs(bcSettings).data('visualSedimentation');
-	
-
-	//barChart.settings.sedimentation.token.size.minimum=0;
-});
-
-var now = new Date();
-
-function reviewAllowSince(dateReview){
-	var diffNowReview = CONFIG.now.getTime() - new Date(dateReview).getTime();
-	var limit = (CONFIG.dayLimit * 24) * 60 * 60 * 1000;
-	if(diffNowReview<=limit){
-		var startDate = limit - diffNowReview;
-		return startDate;
-	}else{
-		return false;
-	}
-}
-
-function generateTimerByMin(time){
-	var timeLimit = (CONFIG.timelineMin*60)*1000;
-	return (time * timeLimit) / ((CONFIG.dayLimit*24)*60*60*1000)
-}
-
-function showHorloge(){
-
-	var timestampDateLimit = CONFIG.now.getTime() - ((CONFIG.dayLimit*24)*60*60*1000);
-	var dateLimit = new Date(timestampDateLimit);
-
-	var diff = CONFIG.now.getTime() - timestampDateLimit;
-
-	var oneHour = (CONFIG.timelineMin * 60 * 1000) / (CONFIG.dayLimit*24);
-	var oneMinute = oneHour / 60;
-
-
-	var wTimerBar = $('.timer-bar').width();
-	var timerBarValue = $('.timer-bar-value');
-	timerBarValue.width(0);
-	var indice = 0;
-
-	setInterval(function(){
-		if(indice>=diff) return;
-		indice = indice + (60 * 1000);
-		var wTimerBarValue = wTimerBar * indice / diff;
-		timerBarValue.width(wTimerBarValue);
-	},oneMinute);
-
+    movieCount: 10,
+    opinionsPerPage: 100,
+    colors: [ "#c00000", "#ffd000", "#008000"],
+    refreshRate: 50
 }
 
-
-
-function getReviewsByFilm(codeFilm){
-/**
-	Nouvelle api avatar note
-    rate, avec une note de 0 à 5
-    wanttosee (note arbitraire de -2... À convertir en vert)
-    notinterested (note arbitraire de -1 À convertir en rouge)
-
-Et maintenant, il y a l'avatar de l'utilisateur (pour ceux qui en ont)
-
-	http://ext.api.allocine.fr/rest/v3/opinionlist?partner=B00015838755&subject=movie:187864&count=100
-**/
-
-	var _movie = {
-		movieCode : codeFilm
-	};
-
-	var reviewCount = 100;
-	//var urlCommentaireMovie = 'http://ext.api.allocine.fr/rest/v3/opinionlist?partner='+ partnerCode +'&subject=movie:'+codeFilm+'&count='+reviewCount;
-	var urlCommentaireMovie = 'http://api.allocine.fr/rest/v3/reviewlist?partner='+ partnerCode +'&format=json&filter=public&count='+reviewCount+'&subject=movie:'+codeFilm;
-	$.getJSON(urlCommentaireMovie, function(data) {
-
-		var nbFilmSince = 0;
-		//console.log(data)
-		var totalResults = data.feed.totalResults;
-		if(totalResults > 0) {
-			var _reviews = new Array();
-			var reviews = data.feed.review;
-			_.each(reviews, function(d){
-				if(d.totalResults == 0) return;
-
-				var dataReview = {
-					commentaire : d.body,
-					date : d.creationDate,//"2013-03-10T
-					rating : d.rating,
-					author : d.writer.name
-				};
-
-				var startDate = reviewAllowSince(d.creationDate);
-
-				if(startDate){
-					nbFilmSince++
-					dataReview.startDate = startDate;
-					_reviews.push(dataReview);
-				}
-			});
-
-			var totalReviews = $('li#movie-'+codeFilm+' span.nbReview').text();
-			$('li#movie-'+codeFilm+' span.nbReview').text(totalReviews-nbFilmSince)
-
-			_movie.reviews = _reviews;
-			_reviewMovies.push(_movie);
-		}
-
-		indiceMovie++;
-		//console.log(indiceMovie)
-		if(indiceMovie == nbMovies){
-			//showHorloge();
-			displayReviews();
-		}
-
-	});//getJson
-}//getReviewsByFilm
-
-function displayReviews(){
-	_.each(_reviewMovies, function(a){
-		console.log(a)
-		var movieCode = a.movieCode;
-		var reviews = a.reviews;
-
-		var barCharCat;
-		$.each(CONFIG.bar, function(k,v){
-			if(movieCode == v)barCharCat = k;
-		});
-
-		_.each(reviews, function(b){
-			
-			b.movieCode = movieCode;
-			var startDate = b.startDate;
-
-			var timer = generateTimerByMin(startDate);
-			setTimeout(function(){
-				addToken(barCharCat, b)
-			},timer);
-		});
-	});
-}//displayReviews
-
-var tokenId = 0;
-
-function addToken(barCharCat, data){
-
-	
-	
-	
+$(function() {
+    
+    var originalStart = new Date().valueOf() - config.originalDuration,
+        timeScale = config.vizDuration / config.originalDuration,
+        movies,
+        moviesToLoad,
+        opinions = [],
+        loadTime = new Date().valueOf(),
+        clockInterval;
+        
+    function resizeTimer() {
+        var w = Math.max(80, $(window).width() - 170),
+            n = Math.min(12, Math.floor(w / 80));
+    	$('.timer-bar').width(w);
+    	var html = '';
+    	for (var k = 0; k < n + 1; k++) {
+    	    html += '<li style="left:'
+    	       + Math.floor(k * w / n)
+    	       + 'px;">'
+    	       + new Date(originalStart + k * config.originalDuration / n).toLocaleTimeString().substr(0,5)
+    	       + '</li>';
+    	}
+        $('.hours').html(html);
+    }
+    
+    resizeTimer();
+    $(window).resize(resizeTimer);
+    
+    var vsHeight = $(window).height() - $('footer').height() - $('header').height() - 300,
+        vsWidth = config.movieCount * 160;
+        
+    $("#data-viz").css('height', vsHeight);
+    $('.posters').css('width', vsWidth);
+    
+    function startViz() {
+        
+        var barChart = undefined;
+        
+        opinions.sort(function(a,b) {
+            return a._timestamp > b._timestamp;
+        });
+        $("#data-viz").html("").css("text-align","left");
+        var barChartSettings = {
+            width : vsWidth,
+            height : vsHeight,
+            chart : {
+                spacer : 5,
+                y: 100,
+                height: vsHeight - 100
+            },
+            data : {
+                model : movies.map(function(movie) {
+                    return {
+                        label: movie.title
+                    };
+                }),
+                strata : function() {
+                    
+                    if (typeof barChart === "undefined") {
+                        var flocculated = [];
+                        _(function() {
+                            _.range(3).map(function(colorId) {
+                                $(".layer_"+colorId).css("fill", config.colors[colorId]);
+                            });
+                        }).defer();
+                    } else {
+                        var flocculated = barChart.selectAll("state",2);
+                    }
+                    
+                    var res = movies.map(function(movie) {
+                        var movieTokens = flocculated.filter(function(t) {
+                            return t.attr("movie") === movie.id;
+                        });
+                        return _.range(3).map(function(colorId) {
+                            var stratumTokens = movieTokens.filter(function(t) {
+                                return t.attr("colorId") === colorId;
+                            }).length;
+                            return {
+                                value: function() {
+                                    return stratumTokens
+                                }
+                            };
+                        });
+                    });
+                    
+                    return res;
+                },
+                stream : {
+                    provider : "tokens",
+                    refresh: config.refreshRate,
+                    now : 0
+                },
+                tokens: opinions.map(function(opinion) {
+                    return {
+                        category: opinion._column,
+                        datetime: opinion.datetime,
+                        movie: opinion._movie,
+                        colorId: opinion._colorId,
+                        fillStyle: opinion._color,
+                        strokeStyle: "#555555",
+                        t: Math.floor((opinion._timestamp - originalStart) * timeScale / config.refreshRate),
+                        shape:{
+                          type:'box',
+                          width:74,
+                          height:5
+                        },
+                        callback:{
+                            suspension: function(token) {
+                                setTimeout(function() {
+                                    token.flocculate();
+                                    barChart.strata.update(barChart);
+                                }, 5000);
+                            }
+                        }
+                    }
+                })
+            },
+            sedimentation: {
+                token: {
+                    size: {
+                        original:12,
+                        minimum:0
+                    }
+                },
+                aggregation:{
+                    height: vsHeight - 100,
+                    maxData: Math.max.apply(Math, movies.map(function(m) { return m.opinions.length; }))
+                },
+                suspension:{
+                    decay:{
+                        power:1.001
+                    }
+                }
+            }
+        }
+        barChart = $("#data-viz").vs(barChartSettings).data('visualSedimentation');
+        var startOfViz = new Date();
+        clearInterval(clockInterval);
+        $(".timer-bar-value").width(0);
+        clockInterval = setInterval(function() {
+            $(".timer-bar-value").width($('.timer-bar').width() * Math.min(1, (new Date() - startOfViz) / config.vizDuration));
+        },
+        100);
+    }
+    
+    function loadMovie(movie) {
+        $.getJSON(
+            "http://api.allocine.fr/rest/v3/opinionlist",
+            {
+                partner: config.partnerCode,
+                format: "json",
+                subject: "movie:" + movie.id,
+                count: config.opinionsPerPage,
+                refresh: refreshtoken(),
+                page: movie.opinionPage
+            },
+            function(d) {
+                if (d.feed && d.feed.activity) {
+                    var tokens = d.feed.activity.filter(function(a) {
+                        return a.action.type !== "notinterested" && a.action.value !== "-3.0";
+                    });
+                } else {
+                    var tokens = [];
+                }
+                tokens.forEach(function(a) {
+                    a._colorId = config.colorIds[a.action.value];
+                    a._color = config.colors[a._colorId];
+                    a._timestamp = new Date(a.datetime).valueOf();
+                    a._movie = movie.id;
+                    a._column = movie.column;
+                });
+                var tokcount = tokens.length;
+                tokens = tokens.filter(function(a) {
+                    return a._timestamp >= originalStart;
+                });
+                movie.opinions = movie.opinions.concat(tokens);
+                opinions = opinions.concat(tokens);
+                $("#data-viz").append(".");
+                if (tokens.length === tokcount) {
+                    console.log("Page " + movie.opinionPage + " of '" + movie.title + "' loaded");
+                    movie.opinionPage ++;
+                    loadMovie(movie);
+                } else {
+                    console.log("Page " + movie.opinionPage + " of '" + movie.title + "' -- total : " + movie.opinions.length + " opinions loaded");
+                    moviesToLoad--;
+                    if (!moviesToLoad) {
+                        console.log("**** Everything is loaded, in " + (new Date().valueOf() - loadTime) / 1000 + " seconds");
+                        startViz();
+                    }
+                }
+            }
+        );
+    }
+        
+    $.getJSON(
+        "http://api.allocine.fr/rest/v3/movielist",
+        {
+            partner: config.partnerCode,
+            format: "json",
+            filter: "top:week",
+            count: config.movieCount,
+            refresh: refreshtoken()
+        },
+        function(d) {
+            $("#data-viz").html("Chargement des flux d'opinions<br />");
+            console.log("Movie List Loaded");
+            movies = d.feed.movie.map(function(movie, i) {
+                return {
+                    id: movie.code,
+                    column: i,
+                    title: movie.title,
+                    poster: movie.poster.href,
+                    opinions: [],
+                    opinionPage: 1
+                }
+            });
+            moviesToLoad = movies.length;
+            movies.forEach(loadMovie);
+            $('.posters').html(movies.map(function(movie) {
+                return '<li><img width="150" height="200" src="'
+                    + movie.poster
+                    + '" alt="'
+                    + movie.title
+                    +'" /></li>';
+            }).join(""));
+        }
+    );
+       
+    function refreshtoken() {
+        return Math.floor(0x100000000 * Math.random()).toString(16) + "-" + (new Date().valueOf() % 0x100000000).toString(16);
+    }
+    
+    $(".rejouer").click(function() {
+        startViz();
+        return false;
+    })
 
-	var commentaire = data.commentaire;
-	var date = data.date;
-	var rating = data.rating;
-	var author = data.author;
-	var movieCode = data.movieCode;
-	var colorid = CONFIG.colorIds[data.rating.toFixed(1)],
-        color = CONFIG.colors[colorid];
-
-	rating = rating.toString().replace(".","_");
-/*
-	var commentReview = 
-	'<div class="comment clearfix" id="token-'+tokenId+'">'+
-		'<span class="comment-arrow"></span>'+
-		'<div class="avatar"><img src="img/profil_50_1.jpg" alt="" /></div>'+
-		'<div class="comment-right">'+
-			'<div class="comment-info clearfix">'+
-				'<span class="username">'+author+'</span>'+
-				'<span class="date">il y a 23 heures</span>'+
-				'<ul class="rating rate-'+rating+'">'+
-					'<li></li><li></li><li></li><li></li><li></li>'+
-				'</ul>'+
-			'</div>'+
-			'<p class="review-content">'+commentaire+'</p>'+
-		'</div>'+
-	'</div>';
-	$('body').append(commentReview);
-*/
-	var token = barChart.addToken({
-		mappingElement : 'token-'+tokenId,
-		commentaire : commentaire,
-		movieCode : movieCode,
-		date : date,
-		rating : rating,
-		author : author,
-	  	category: barCharCat,
-	  	colorId: colorid,
-	  	fillStyle: color,
-	  	strokeStyle: "#555555",
-
-        shape:{
-          type:'box',
-          width:74,
-          height:5
-        },
-	  	callback:{
-/*
-	  		draw : function(token){
-	  			var myDomElement= $('#'+token.attr('mappingElement'))[0];
-                $(myDomElement).css({
-                  top : token.attr('y') + 150,
-                  left : token.attr('x')
-                })
-	  		},
-            mouseover:function(token){
-            	$('#'+token.attr('mappingElement')).show();
-            	var myDomElement= $('#'+token.attr('mappingElement'))[0];
-            	var commentaire = token.attr('commentaire'),
-            		author = token.attr('author'),
-            		date = token.attr('date'),
-            		movieCode = token.attr('movieCode'),
-            		rating = token.attr('rating');
-            },
-            mouseout:function(token){
-            	$('#'+token.attr('mappingElement')).hide();
-            },
-            */
-            suspension: function(token) {
-                setTimeout(function() {
-                    token.flocculate();
-                    barChart.strata.update(barChart);
-                }, 5000);
-            }
-     	}
-	});
-	tokenId++;
-}
-
-
-
-
-
-$('a.rejouer').bind('click', function(e){
-	e.preventDefault();
-	addTokenTest()
-});
-
-function addTokenTest(){
-	barChart.addToken({
-	  	category:0,
-	  	size:1,
-
-	  	callback:{
-            
-     	}
-	});
-}
-});//load
\ No newline at end of file
+});
\ No newline at end of file