var myDir = new IriSP.Model.Directory(),
    myProject = myDir.remoteSource({
            url: project_url,
            serializer: IriSP.serializers.ldt
        });

myProject.onLoad(function() {
    
    $(".project-title").text(myProject.title);
    
    var myMedia = myProject.getCurrentMedia();
    
    IriSP.htmlPlayer(
        myMedia,
        $(".video-container"),
        {
            width: 1000,
            height: 560,
            autostart: true,
            url_transform: function(src) {
                return [{
                    type: "video/mp4",
                    src: src.replace(/\.[\d\w]+$/,'.mp4').replace('rtmp://media.iri.centrepompidou.fr/ddc_player', 'http://media.iri.centrepompidou.fr')
                }, {
                    type: "video/webm",
                    src: src.replace(/\.[\d\w]+$/,'.webm').replace('rtmp://media.iri.centrepompidou.fr/ddc_player', 'http://media.iri.centrepompidou.fr')
                }];
            }
        }
    );
    
    myMedia.on("timeupdate", function(t) {
        var progress = $(".progress-indicator"),
            pos = ($(".chapters-bar").width() - 2 * progress.width()) * t / myMedia.duration;
        progress.css("left",pos);
    });
    myMedia.on("play", function() {
        $(".play-button").addClass("pause");
    });
    myMedia.on("pause", function() {
        $(".play-button").removeClass("pause");
    });
    
    var tags = myProject.getTags().sortBy(function(t) {
            return - t.getRelated("annotation").length;
        }).slice(0,12),
        tagTemplate = _.template('<li data-tag-id="<%- id %>" class="tag"><%- title %></li>'),
        clickedTag = null,
        lastTag = null;
    
    $(".tags-list").html(tags.map(tagTemplate).join(""));
    
    $(".tags-title").mouseenter(function() {
        $(".tags-list").slideDown();
    });
    $(".tags").mouseleave(function() {
        $(".tags-list").slideUp();
    });
    
    $("body").click(function() {
        if (clickedTag) {
            $(".found").removeClass("found");
            clickedTag = null;
        }
        return false;
    });
    
    function showTag(tagId) {
        $(".found").removeClass("found");
        var tag = myProject.getElement(tagId);
        if (tag) {
            tag.getRelated("annotation").forEach(function(a) {
                a.trigger("found-tags");
            });
            $(".tag[data-tag-id="+tagId+"]").addClass("found");
        }
        lastTag = tagId;
    }
    
    $(".tag").hover(function() {
        showTag($(this).attr("data-tag-id"));
    }, function() {
        showTag(clickedTag);
    }).click(function() {
        clickedTag = lastTag;
        return false;
    });
    
    
    var chapters = myProject.getAnnotationsByTypeTitle("chapitrage"),
        chapterTemplate = _.template(
            '<li class="chapter" style="left: <%- 100*begin/getMedia().duration %>%; width: <%- 100*getDuration()/getMedia().duration %>%;">'
            + '<div class="chapter-block"></div><div class="chapter-title"><%- title %></div></li>'
        ),
        chapterList = $(".chapters-list"),
        hoveredChapter = null,
        currentChapter = null,
        currentChapterI = 0;
    
    function highlightChapter() {
        $(".chapter").removeClass("active");
        if (hoveredChapter || currentChapter) {
            (hoveredChapter || currentChapter).addClass("active");
        }
    }
    
    chapters.forEach(function(chapter, i) {
        var element = $(chapterTemplate(chapter));
        element.click(function() {
           myMedia.setCurrentTime(chapter.begin); 
           return false;
        }).hover(function() {
            hoveredChapter = element;
            highlightChapter();
        }, function() {
            hoveredChapter = null;
            highlightChapter();
        });
        chapter.on("enter", function() {
            currentChapter = element;
            currentChapterI = i;
            if (i) {
                $(".prev-chapter").removeClass("inactive");
            } else {
                $(".prev-chapter").addClass("inactive");
            }
            if (i < chapters.length - 1) {
                $(".next-chapter").removeClass("inactive");
            } else {
                $(".next-chapter").addClass("inactive");
            }
            highlightChapter();
        });
        chapter.on("leave", function() {
            currentChapter = null;
            highlightChapter();
        });
        chapter.on("found-tags", function() {
            element.addClass("found");
        });
        chapterList.append(element);
    });
    
    $(".prev-chapter").click(function() {
        if (currentChapterI) {
            myMedia.setCurrentTime(chapters[currentChapterI - 1].begin);
        }
        return false;
    });
    $(".next-chapter").click(function() {
        if (currentChapterI < chapters.length - 1) {
            myMedia.setCurrentTime(chapters[currentChapterI + 1].begin);
        }
        return false;
    });
    
    $(".play-button").click(function() {
        if (myMedia.paused) {
            myMedia.play();
        } else {
            myMedia.pause();
        }
        return false;
    });
    
    $(".progress-indicator").draggable({
        axis: "x",
        containment: "parent",
        drag: function(e, ui) {
            var t = myMedia.duration * parseInt(ui.helper.css("left")) / ( $(".chapters-bar").width() - 2 * ui.helper.width() );
            myMedia.setCurrentTime(t);
        }
    });
    
    var pictoTemplate = _.template(
        '<li class="<%- type %>"><span class="picto"><a href="#"></a></span>'
        + '<span class="picto-title"><%- annotation.title %></span></li>'
    );
    
    var chipTemplate = _.template(
        '<li class="chip <%- type %><%- left %>" style="left: <%- pos %>%"><div class="chip-circle">'
        + '</div><div class="chip-pole"></div><div class="chip-title"><%- annotation.title %></div></li>'
    );
    
    var annotations = myProject.getAnnotationsByTypeTitle("annotations").sortBy(function(a) {
        return a.begin;
    });
    
    var annotationinfos = annotations.map(function(annotation) {
        var annotationinfo = {
            annotation: annotation,
            open: false,
            pos: 100 * annotation.begin / annotation.getMedia().duration
        };
        annotationinfo.left = (annotationinfo.pos > 80 ? " left": "");
        switch(annotation.content.mimetype) {
            case "application/x-ldt-slideshow":
                annotationinfo.type = "slideshow";
            break;
            case "application/x-ldt-video":
                annotationinfo.type = "video";
            break;
            case "application/x-ldt-audio":
                annotationinfo.type = "audio";
            break;
            case "application/x-ldt-links":
                annotationinfo.type = "link";
            break;
            default:
                annotationinfo.type = "text";
        }
        annotationinfo.picto = $(pictoTemplate(annotationinfo)).appendTo(".pictolist");
        annotationinfo.chip = $(chipTemplate(annotationinfo)).appendTo(".chips-list");
        annotationinfo.both = annotationinfo.picto.add(annotationinfo.chip);
        annotationinfo.both.click(function() {
                openAnnotation(annotationinfo);
                return false;
            })
            .hover(function() {
                annotationinfo.both.addClass("hover");
            }, function() {
                annotationinfo.both.removeClass("hover");
            });
        annotation.on("enter", function() {
            annotationinfo.picto.show().animate({
                height: "38px",
                opacity: 1
            }, 800);
        });
        annotation.on("leave", function() {
            annotationinfo.picto.animate({
                height: 0,
                opacity: 0
            }, 800, function() {
                annotationinfo.picto.hide();
            });
        });
        annotation.on("found-tags", function() {
            annotationinfo.both.addClass("found");
        });
        return annotationinfo;
    });
    
    currentAnnotation = null;
    
    function openAnnotation(annotationinfo) {
        
        if (currentAnnotation === annotationinfo) {
            closeAnnotation(true);
            return;
        }
        
        if (myMedia.currentTime < annotationinfo.annotation.begin || myMedia.currentTime > annotationinfo.annotation.end) {
            myMedia.setCurrentTime(annotationinfo.annotation.begin);
        }
        
        myMedia.pause();
        closeAnnotation(false);
        
        currentAnnotation = annotationinfo;
        
        annotationinfo.both.addClass("current");
        
        $(".chapters-bar").addClass("annotation-onscreen");
        
        var annotationDiv = $(".annotation-templates ." + annotationinfo.type + "-annotation").clone();
        
        annotationDiv.appendTo($(".main-video"));
        annotationDiv.find(".close-annotation").click(closeAnnotation);
        annotationDiv.find(".annotation-title").text(annotationinfo.annotation.title);
        
                
        var positionDiv = function(anim) {
            var css = {
                top: Math.floor(($(".main-video").height() - annotationDiv.height())/2)+"px"
            };
            if (anim) {
                annotationDiv.animate(css, 800);
            } else {
                annotationDiv.css(css);
            }
        }
        
        switch (annotationinfo.type) {
            
            case "slideshow":
                
                var currentslide = 0,
                    slideInterval,
                    playing = false,
                    loaded = false,
                    slides = annotationinfo.annotation.content.images;
                
                var resizeImage = function() {
                    var imgel = annotationDiv.find(".slideshow-image");
                    imgel.css("margin-top","");
                    var w = imgel.width(),
                        h = imgel.height();
                    annotationDiv.find(".annotation-main").css("height","");
                    annotationDiv.find(".slideshow-description").css("margin-left",w);
                    var h2 = annotationDiv.find(".annotation-main").height();
                    if (h < h2) {
                        imgel.css("margin-top",Math.floor((h2-h)/2)+"px");
                    }
                    if (+imgel.css("opacity") !== 1) {
                        imgel.fadeTo(400, 1);
                    }
                }
                
                var showCurrentImage = function() {
                    var slide = slides[currentslide];
                    annotationDiv.find(".slideshow-image").attr({
                        src: slide.image.src,
                        title: slide.title,
                        alt: slide.title
                    });
                    annotationDiv.find(".slideshow-title").text(slide.title);
                    annotationDiv.find(".slideshow-description").html(
                        slide.description.split(/\n/gm).map(function(l) {
                            return '<p>' + _.escape(l) + '</p>';
                        }).join("")
                    );
                    resizeImage();
                }
                
                var nextImage = function() {
                    currentslide = (currentslide + 1) % slides.length;
                    annotationDiv.find(".slideshow-image").fadeTo(400, 0, showCurrentImage);
                    return false;
                }
                
                var togglePlay = function() {
                    playing = !playing;
                    clearInterval(slideInterval);
                    if (playing) {
                        slideInterval = setInterval(nextImage,Math.max(1000,annotationinfo.annotation.content.slideduration || 0));
                        annotationDiv.find(".slideshow-play-pause").addClass("pause");
                    } else {
                        annotationDiv.find(".slideshow-play-pause").removeClass("pause");
                    }
                    return false;
                }
                
                var checkloaded = function() {
                    if (loaded) {
                        return;
                    }
                    loaded = slides.reduce(function(mem, slide) {
                        return (mem && !!slide.image && !!slide.image.width);
                    }, true);
                    if (loaded) {
                        showCurrentImage();
                        if (annotationinfo.annotation.autostart && slides.length > 1) {
                            togglePlay();
                        }
                    }
                }
                
                slides.forEach(function(slide) {
                    slide.image = new Image();
                    slide.image.onload = checkloaded;
                    slide.image.src = slide.url;
                });
                
                checkloaded();
                
                if (slides.length > 1) {
                    annotationDiv.find(".slideshow-next").click(nextImage);
                    annotationDiv.find(".slideshow-previous").click(function() {
                        currentslide = (currentslide ? currentslide : slides.length) - 1;
                        annotationDiv.find(".slideshow-image").fadeTo(400, 0, showCurrentImage);
                    });
                    annotationDiv.find(".slideshow-play-pause").click(togglePlay);
                } else {
                    annotationDiv.find(".slideshow-next, .slideshow-previous, .slideshow-play-pause").hide();
                }
                
            break;
            
            case "audio":
            case "video":
            
                var src = annotationinfo.annotation.content.url;
            
                var youtubeTemplate = _.template(
                    '<iframe width="<%- width %>" height="<%- height %>" src="http://www.youtube.com/embed/<%- ytid %>?rel=0&autoplay=<%- autoplay %>" frameborder="0"></iframe>'
                );
                
                var htmlTemplate = _.template(
                    '<<%- type %> width="<%- width %>" controls="true" autoplay="<%- autoplay %>" src="<%- src %>"/>'
                );
                
                var mediaW = (annotationinfo.type === "audio" ? "100%" : "650"),
                    mediaH = (annotationinfo.type === "audio" ? "60" : "420");
        
                annotationDiv.find(".media-description").html(
                    annotationinfo.annotation.description.split(/\n/gm).map(function(l) {
                        return '<p>' + _.escape(l) + '</p>';
                    }).join("")
                );
                
                if (/^(https?:\/\/)?(www\.)?youtu\.?be/.test(src)) {
                    var urlparts = src.split(/[?&]/g),
                        ytid = "",
                        vtest = /^v=/;
                    urlparts.slice(1).forEach(function(p) {
                        if (/^v=/.test(p)) {
                            ytid = p.replace(vtest,"");
                        }
                    });
                    if (!ytid) {
                        ytid = (urlparts[0].match(/[^\/]+$/) || [""])[0];
                    }
                    annotationDiv.find(".media-frame").html(youtubeTemplate({
                        ytid: ytid,
                        width: mediaW,
                        height: mediaH,
                        autoplay: +annotationinfo.annotation.content.autostart
                    }));
                    break;
                }
                
                if (/^(https?:\/\/)?(www\.)?vimeo/.test(src)) {
                    $.ajax({
                        url: "http://vimeo.com/api/oembed.json",
                        dataType: "jsonp",
                        data: {
                            width: mediaW,
                            height: mediaH,
                            url: src,
                            autoplay: annotationinfo.annotation.content.autostart,
                            color: "B8155F",
                            portrait: false,
                            title: false,
                            byline: false
                        },
                        success: function(data) {
                            annotationDiv.find(".media-frame").html(data.html);
                            positionDiv(true);
                        }
                    });
                    return;
                }
                
                if (/^(https?:\/\/)?(www\.)?dailymotion/.test(src)) {
                    $.ajax({
                        url: "http://www.dailymotion.com/services/oembed",
                        dataType: "jsonp",
                        data: {
                            format: "json",
                            maxwidth: mediaW,
                            maxheight: 487,
                            url: src
                        },
                        success: function(data) {
                            annotationDiv.find(".media-frame").html(data.html);
                            positionDiv(true);
                        }
                    });
                    return;
                }
                
                if (/^(https?:\/\/)?(www\.)?soundcloud\.com/.test(src)) {
                    $.ajax({
                        url: "http://soundcloud.com/oembed",
                        dataType: "jsonp",
                        data: {
                            format: "js",
                            show_comments: false,
                            auto_play: annotationinfo.annotation.content.autostart,
                            show_artwork: false,
                            url: src,
                            color: "B8155F"
                        },
                        success: function(data) {
                            annotationDiv.find(".media-frame").html(data.html);
                            positionDiv(true);
                        }
                    });
                    return;
                }
                
                var extension = (src.match(/\.([\d\w]+)$/) || ["",""])[1],
                    mimetype = annotationinfo.type + "/" + extension,
                    fallbacks = { "video/webm": "mp4", "video/mp4": "webm" },
                    canPlay = document.createElement("video").canPlayType(mimetype);
                
                if (!canPlay) {
                    src = src.replace(/\.[\d\w]+$/,"." + fallbacks[mimetype]);
                }
                
                var media = $(htmlTemplate({
                    type: annotationinfo.type,
                    src: src,
                    width: mediaW,
                    height: mediaH,
                    autoplay: "" + annotationinfo.annotation.content.autostart
                }));
                
                media.on("loadedmetadata", function() {
                    positionDiv(true);
                });
                
                annotationDiv.find(".media-frame").html(media);
                return;
                
            break;
            
            case "text":
                
                var text = annotationinfo.annotation.content.text || annotationinfo.annotation.description;
                
                switch (annotationinfo.annotation.content.markup) {
                    case "html":
                        annotationDiv.find(".text-contents").html(text);
                    break;
                    default:
                        annotationDiv.find(".text-contents").html(
                            text.split(/\n/gm).map(function(l) {
                                return '<p>' + _.escape(l) + '</p>';
                            }).join("")
                        );
                    break;
                }
                annotationDiv.find(".text-contents a").attr("target","_blank");
                
            break;
            
            case "link":
            
                var linkTemplate = _.template('<p><a href="<%- url %>" target="_blank"><%- title %></a></p>');
                
                annotationDiv.find(".link-contents").html(
                    annotationinfo.annotation.content.links.map(linkTemplate).join("")
                );
                
            break;
        }
        
        positionDiv(true);
        
    }
    
    $(".video-container").click(function() {
        if (currentAnnotation) {
            closeAnnotation(true);
        }
        return false;
    });
   
    function closeAnnotation(e) {
        currentAnnotation = null;
        $(".chip, .pictolist li").removeClass("current");
        $(".chapters-bar").removeClass("annotation-onscreen");
        $(".annotation audio, .annotation video").each(function() {
            try {
                this.pause();
            } catch(e) { }
        });
        $(".main-video .annotation").hide().remove();
        if (!!e) {
            myMedia.play();
        }
        return false;
    }
   
});
