$(function(){

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

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

$('a.more').bind('click', function(e){
	e.preventDefault();
	var target = $(this).attr('href');
	if($(target).hasClass('less')){
		$(target).removeClass('less');
		$(this).addClass('less');
	}else{
		$(target).addClass('less');
		$(this).removeClass('less');
	}	
});// a.more

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

$('[data-image*="{stickers_base}"]').each(function() {
	var el = $(this);
	el.attr("data-image", el.attr("data-image").replace("{stickers_base}",stickers_base));
});

//-- API allocine

//-- movie
var urlMovie = 'http://api.allocine.fr/rest/v3/movie?partner='+partnerCode+'&code='+ idMovie;
$.getJSON(urlMovie, function(data) {
	var movie = data.movie;

	//-- title
	$('.wrap-top .movie-title').text(movie.title);
	$('.wrap-top .movie-year').text(movie.productionYear);

	//-- stars
	var castMember = movie.castMember;

	$.each(castMember, function(k, v){
		var name =	v.person.name;
		var codeActor = v.person.code;
		var urlPicture;
		if(v.picture !== undefined) {
			urlPicture = v.picture.href;
		}else{
			urlPicture = 'http://fr.web.img3.acsta.net/c_160_213/b_1_d6d6d6/commons/emptymedia/empty_star.jpg';
		}	
		var urlFichePersonne = 'http://www.allocine.fr/personne/fichepersonne_gen_cpersonne='+codeActor+'.html';
		var itemStar = 
			'<li class="cinecard-draggable" draggable="true">'+
				'<a class="tool-info" target="_blank" href="'+ urlFichePersonne +'" data-title="'+ name +'">'+
					'<img src="'+ urlPicture +'" alt="'+ name +'" />'+
				'</a>'+
			'</li>';
		$('#stars-more').append(itemStar);
	});	

	/* Creating Renkan Template */
	var _posterData = {
			title: movie.title,
			image: movie.poster.href,
			uri: _(movie.link).find(function(l) { return l.rel === "aco:web" }).href,
			position: {
				x: 0,
				y: 0
			},
			description: "Affiche du film",
			size: 4
		},
		_stickers = [
			"pourquoi-j-ai-aime.png",
			"pourquoi-le-voir.png",
			"secrets-et-bonus.png",
			"message-perso.png"
		],
		_startAngle = Math.PI / 6,
		_stickerDistance = 220,
		_filmNode = _renkan.project.addNode(_posterData);
		
	_(_stickers).each(function(v, k) {
		var _a = _startAngle + 2 * Math.PI * k / _stickers.length,
			_stickerData = {
				title: " ",
				position: {
					x: _stickerDistance * Math.cos(_a),
					y: - _stickerDistance * Math.sin(_a)
				},
				image: stickers_base + v,
				size: 0
			}
		_stickerNode = _renkan.project.addNode(_stickerData);
		var _edgeData = {
			from: _filmNode,
			to: _stickerNode
		}
		_renkan.project.addEdge(_edgeData);
	});


});

//-- picture
var urlPicture = 'http://api.allocine.fr/rest/v3/picturelist?partner='+partnerCode+'&subject=movie:'+ idMovie;
$.getJSON(urlPicture, function(data) {
	var media = data.feed.media;
	$.each(media, function(k, v){
		var urlThumb = v.thumbnail.href;
		var rcode = v.rcode;
		var title = v.title;
		var urlAllocine = 'http://www.allocine.fr/film/fichefilm-'+ idMovie +'/photos/detail/?cmediafile='+ rcode;
		var itemImagess = 
			'<li class="cinecard-draggable" draggable="true">'+
				'<a class="tool-info" target="_blank" href="'+ urlAllocine +'" data-title="'+title+'">'+
					'<img src="'+ urlThumb +'" alt="'+title+'" />'+
				'</a>'+
			'</li>';
		$('#images-more').append(itemImagess);
	});
	resizeImg('#images-more');
});//get

//-- trailer
var urlTrailers = 'http://api.allocine.fr/rest/v3/videolist?partner='+partnerCode+'&mediafmt=flv&subject=movie:'+ idMovie;
$.getJSON(urlTrailers, function(data) {
	var media = data.feed.media;
	$.each(media, function(k, v){
		console.log(v)
		var urlThumbnail = v.thumbnail.href;
		var title = v.title;
		var code = v.code;
		var url = 'http://www.allocine.fr/video/player_gen_cmedia='+code+'&cfilm='+idMovie+'.html';
		var itemVideo = 
			'<li class="cinecard-draggable" draggable="true">'+
				'<a class="tool-info" target="_blank" href="'+ url +'" data-title="'+title+'">'+
					'<img src="'+ urlThumbnail +'" alt="'+title+'" />'+
				'</a>'+
			'</li>';
		$('#videos-more').append(itemVideo);
		resizeImg('#videos-more');
	});
});


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

//TOOLTIP
var show_tooltip_info_iri = function(elem){
	var tooltip = $('.rate_tooltip'),
		name = elem.attr('data-title'),
		arrow = tooltip.find('.arrow_l'),
		top = elem.offset().top,
		right = elem.offset().left + elem.width() + arrow.width();
	tooltip.find('p').text(name)
	tooltip.show();
	tooltip.css({
		top : top,
		left : right
	});
}
var hide_tooltip_info_iri = function(elem){
	var tooltip = $('.rate_tooltip');
	tooltip.hide();
}
$(document).on({
    mouseenter: function() {
    	show_tooltip_info_iri($(this));
	},
    mouseleave: function() {
    	hide_tooltip_info_iri($(this));
    }
}, 'a.tool-info');

//Renkan initialization
var _renkan = new Rkns.Renkan({
    user_id: "u-iri",
    language: "fr_cg",
    container: "cinecard",
    show_bins: false,
    show_top_bar: false,
    show_minimap: false,
    show_node_circles: false,
    clip_node_images: false,
    size_bug_fix: false,
    allow_double_click: false,
    node_size_base: 40,
    default_user_color: "#808080",
    static_url: renkan_base
});

var elementDropped = false;

// Attach drag and drop events
$(".sidebar")
	.on("mousemove", ".cinecard-draggable", function(e) {
		try {
			this.dragDrop();
		}
		catch(err) {}
    })
    .on("dragstart", ".cinecard-draggable", function(e) {
    	$(".cinecard-draggable").css("opacity", .5);
    	$(this).css("opacity",1);
    	var div = document.createElement('div');
    	div.appendChild(this.cloneNode(true));
		try {
			e.originalEvent.dataTransfer.setData("text/html",div.innerHTML);
		}
		catch(err) {
			e.originalEvent.dataTransfer.setData("text",div.innerHTML);
		}
    })
    .on("dragend", ".cinecard-draggable", function(e) {
    	$(".cinecard-draggable").css("opacity", 1);
    })
    .on("touchstart", ".cinecard-draggable", function(e) {
		elementDropped = false;
    	$(".cinecard-draggable").css("opacity", .5);
    	$(this).css("opacity",1);
	})
	.on("touchmove", ".cinecard-draggable", function(e) {
		e.preventDefault();
		var touch = e.originalEvent.changedTouches[0],
			off = _renkan.renderer.canvas_$.offset(),
			w = _renkan.renderer.canvas_$.width(),
			h = _renkan.renderer.canvas_$.height();
		if (touch.pageX >= off.left && touch.pageX < (off.left + w) && touch.pageY >= off.top && touch.pageY < (off.top + h)) {
			if (elementDropped) {
				_renkan.renderer.onMouseMove(touch, true);
			} else {
				elementDropped = true;
	        	var div = document.createElement('div');
	        	div.appendChild(this.cloneNode(true));
				_renkan.renderer.dropData({"text/html": div.innerHTML}, touch);
				_renkan.renderer.onMouseDown(touch, true);
			}
		}
	})
	.on("touchend", ".cinecard-draggable", function(e) {
    	$(".cinecard-draggable").css("opacity", 1);
		if (elementDropped) {
			_renkan.renderer.onMouseUp(e.originalEvent.changedTouches[0], true);
		}
		elementDropped = false;
	});

$(".send").click(function() {
	alert("Save JSON data:\n\n" + JSON.stringify(_renkan.project.toJSON()));
});

});