$(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 : []
};

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();

function resizeImg(parentId){
	$(parentId+" 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
	        });
	    });
	});
}



var bcSettings = {
	width : 960,
	height : CONFIG.hVS,
	chart : {
		spacer : 5
	},
	data : {
		model :[],
		strata:[],
		stream : { provider : 'direct' }
	},
	sedimentation:{
	    token:{
	      size:{original:12,minimum:2}
	    },
	    aggregation:{height:100},
	    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 urlBestMovies = 'http://api.allocine.fr/rest/v3/movielist?partner='+ partnerCode +'&format=json&filter=top:week&count=15';
$.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){

		var dataMovie = {
			title : d.originalTitle,
			code : d.code,
			posterUrl : d.poster.href,
			userRating : d.statistics.userRating,
			userReviewCount : d.statistics.userReviewCount
		};

		var poster = 
			'<li>'+
				'<img 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"});

		var userReviewCount = dataMovie.userReviewCount;
		if(_.isUndefined(userReviewCount))userReviewCount = 0;
		var initValue = userReviewCount;

		initValue = 0;

		bcSettings.data.strata.push([{initValue: initValue }]);

	});

	resizeImg('.posters');
	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;

	rating = rating.toString().replace(".","_");
	console.log(rating);

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


	barChart.addToken({
		mappingElement : 'token-'+tokenId,
		commentaire : commentaire,
		movieCode : movieCode,
		date : date,
		rating : rating,
		author : author,
	  	category:barCharCat,
	  	size:10,
/*
shape:{
  type:'box',
  width:75,
  height:2.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();
            }
     	}
	});
	tokenId++;
}





$('a.rejouer').bind('click', function(e){
	e.preventDefault();
	addTokenTest()
});

function addTokenTest(){
	barChart.addToken({
	  	category:0,
	  	size:1,

	  	callback:{
            
     	}
	});
}
});//load