$(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

var stickerlist = [
    {
        description: "Tu vas aimer",
        image: "tu-vas-aimer.png",
        loadAtStart: false
    },
    {
        description: "À lire",
        image: "a-lire.png",
        loadAtStart: false
    },
    {
        description: "Me rappelle",
        image: "me-rappelle.png",
        loadAtStart: false
    },
    {
        description: "Pourquoi j'ai aimé",
        image: "pourquoi-j-ai-aime.png",
        loadAtStart: true
    },
    {
        description: "À voir",
        image: "a-voir.png",
        loadAtStart: true
    },
    {
        description: "Message perso",
        image: "message-perso.png",
        loadAtStart: true
    },
];

var stickerTemplate = _.template(
    '<li class="cinecard-draggable" draggable="true" data-title="none" data-description="<%-description %>" data-image="<%- stickers_base + image %>" data-uri="none">'
    + '<a><img src="<%- stickers_base + image %>" /></a></li>'
    )

$('.stickers').html(stickerlist.map(stickerTemplate).join(""));

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

var acimgserv = 0,
    acimgservcount = 6;

window.resizeAcPicture = function(pic, w, h) {
    var path = pic.path || pic.href || pic || "";
    if (/^https?:\/\//.test(path)) {
        path = path.replace(/^https?:\/\/[^\/]+/,'');
    }
    return "http://fr.web.img"
        + ( 1 + (acimgserv++ % acimgservcount))
        + ".acsta.net/r_"
        + w
        + "_"
        + h
        + path
}

var apiBase = 'http://api.allocine.fr/rest/v3/';

//Getting Movie/Series Metadata

var starTemplate = _.template(
    '<li class="cinecard-draggable" draggable="true">'
        + '<a class="tool-info" target="_blank" href="http://www.allocine.fr/personne/fichepersonne_gen_cpersonne=<%- person.code %>.html" data-title="<%- person.name %>, <%- activity["$"] %><% if (typeof role !== "undefined") { print(" (" + role + ")"); } %>">'
            + '<img src="<% if (typeof picture !== "undefined") { print(resizeAcPicture(picture,232,312)); } else { print(resizeAcPicture("/commons/emptymedia/empty_star.jpg",58, 78)); } %>" alt="Photo de <%- person.name %>" />'
        + '</a>'
    + '</li>'
);

$.getJSON(
    apiBase + programmeType,
    {
        partner: partnerCode,
        code: programmeCode
    },
    function(data) {
        
        var programme = data[programmeType];
    
        //-- title
        $('.wrap-top .movie-title').text(programme.title);
        $('.wrap-top .movie-year').text(programme.productionYear || programme.yearStart || "");
    
        //-- stars
        $('#stars-more').html(programme.castMember.map(starTemplate).join(""));    
    
        /* Creating Renkan Template */
        var _posterData = {
                title: programme.title,
                image: programme.poster.href,
                uri: _(programme.link).find(function(l) { return l.rel === "aco:web" }).href,
                position: {
                    x: 0,
                    y: 0
                },
                description: "Affiche du film",
                size: 4
            },
            _startAngle = Math.PI / 6,
            _stickerDistance = 220,
            _filmNode = _renkan.project.addNode(_posterData);
            
        stickerlist.filter(function(s) {
            return s.loadAtStart;
        }).forEach(function(v, k, l) {
            var _a = _startAngle + 2 * Math.PI * k / l.length,
                _stickerData = {
                    title: "",
                    description: v.description,
                    position: {
                        x: _stickerDistance * Math.cos(_a),
                        y: -_stickerDistance * Math.sin(_a)
                    },
                    image: stickers_base + v.image,
                    size: 0
                },
                _stickerNode = _renkan.project.addNode(_stickerData),
                _edgeData = {
                    from: _filmNode,
                    to: _stickerNode
                }
            _renkan.project.addEdge(_edgeData);
        });

    }
);

//Getting Pictures Metadata

var picTemplate = _.template(
    '<li class="cinecard-draggable" draggable="true">'
        + '<a class="tool-info" target="_blank" href="http://www.allocine.fr/'
        + '<% if (programmeType === "movie") { print("film/fichefilm") } else { print("series/ficheserie") } %>-'
        + '<%- programmeCode %>/photos/detail/?cmediafile=<%- rcode %>" data-title="<%- title %>">'
            + '<img src="<%- resizeAcPicture(thumbnail,800,600) %>" alt="<%- title %>" />'
        + '</a>'
    + '</li>'
);

$.getJSON(
    apiBase + 'picturelist',
    {
        partner: partnerCode,
        subject: programmeType + ':' + programmeCode,
        count: 30
    },
    function(data) {
        $('#images-more').html(data.feed.media.map(picTemplate).join(""));
        resizeImg('#images-more');
    }
);

//Getting Videos Metadata

var videoTemplate = _.template(
    '<li class="cinecard-draggable" draggable="true">'
        + '<a class="tool-info" target="_blank" href="http://www.allocine.fr/blogvision/<%- code %>" data-title="<%- title %>">'
            + '<img src="<%- resizeAcPicture(thumbnail,800,600) %>" alt="<%- title %>" />'
        + '</a>'
    + '</li>'
);

$.getJSON(
    apiBase + 'videolist',
    {
        partner: partnerCode,
        subject: programmeType + ':' + programmeCode,
        count: 30
    },
    function(data) {
        $('#videos-more').html(data.feed.media.map(videoTemplate).join(""));
        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
function show_tooltip_info_iri(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
    });
}
function hide_tooltip_info_iri(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",
    buttons_background: "#101010",
    static_url: renkan_base,
    label_untitled_nodes: false,
    show_node_editor_color: false,
    show_node_editor_size: false,
    show_node_editor_image: false,
    show_node_editor_uri: false,
    show_edge_editor_uri: false
});

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

});