$(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:{
    	aggregation:{height:100}
  	},
  	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({});

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

		initValue = 0;

		bcSettings.data.strata.push([{initValue: initValue }]);
/*
		var item = $('<li>').attr('data-poster', dataMovie.posterUrl).attr('id', 'movie-'+dataMovie.code ).attr('id', 'movie-'+dataMovie.code ).css('width', wItem);
		var nbReview = $('').addClass('nbReview').text(userReviewCount);
		item.append(nbReview);
		item.appendTo('.info-movies');
*/
	});

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

	var _movie = {
		movieCode : codeFilm
	};

	var reviewCount = 100;
	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){
		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

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 nbReview = $('li#movie-'+movieCode+' span.nbReview').text();
	var newNbReview = parseInt(nbReview)+1;
	$('li#movie-'+movieCode+' span.nbReview').text(newNbReview);
	//console.log(data.author)
	barChart.addToken({
		commentaire : commentaire,
		movieCode : movieCode,
		date : date,
		rating : rating,
		author : author,
	  	category:barCharCat,
	  	size:1,
shape:{
  type:'box',
  width:75,
  height:2.5
},
	  	callback:{
            mouseover:function(token){
            	var commentaire = token.attr('commentaire');
            	var author = token.attr('author');
            	var date = token.attr('date');
            	var movieCode = token.attr('movieCode');
            	$('.review .author').text(author+', '+date);
            	$('.review .comment').text(commentaire);
            	var poster = $('li#movie-'+movieCode).attr('data-poster');
            	$('.review img').attr('src', poster);
            }
     	}
	});
}

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

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

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