$(function(){

/*
$(window).bind('resize', function(){
	setSidebarContentHeight();
});
setSidebarContentHeight();
function setSidebarContentHeight(){
	var newHeight = $(window).height() - $('header').height() - $('footer').height();
	$(".sidebar .content").css('height', newHeight);
}

*/



var CONFIG = {
	wChart : 150,
	hVS : 200,
	now : new Date(),
	dayLimit : 1,
	timelineMin : 5,
	bar : [],
    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);

}



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){

	
	
	

	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