$(function(){

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


$(".central").mCustomScrollbar({
	advanced:{
	    updateOnContentResize: true
	}
});

*/
function init(){
	var wWin = ($(window).width()>520) ? $(window).width() : 520;
	$('.timer-bar').width(wWin - 170);


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

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

var bcSettings = {
	width : 960,
	height : 400,
	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;

		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 = $('<span>').addClass('nbReview').text(userReviewCount);
		item.append(nbReview);
		item.appendTo('.info-movies');
*/
	});

	resizeImg('.posters');
	barChart = $("#data-viz").vs(bcSettings).data('visualSedimentation');

});
/*
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;

	displayHorloge(timestampDateLimit);

	setInterval(function(){
		if(timestampDateLimit>=CONFIG.now.getTime()) return;
		timestampDateLimit = timestampDateLimit + (60 * 1000);
		displayHorloge(timestampDateLimit);
	},oneMinute);

}

function displayHorloge(timestampDateLimit){
	timestampDateLimit = timestampDateLimit+(60*1000);
	var dateLimit = new Date(timestampDateLimit);
	var horlogeHour = dateLimit.getHours();
	var horlogeMin = dateLimit.getMinutes();
	if(horlogeMin.toString().length==1)horlogeMin = '0'+horlogeMin;
	var horlogeDay = dateLimit.getDate();
	var horlogeMonth = dateLimit.getMonth()+1;
	$('.horloge').html(horlogeDay+' / '+horlogeMonth+'<br/>'+horlogeHour+'h'+horlogeMin);
}

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:3,
	  	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);
            }
     	}
	});
}
*/
});//load