var myMedia = null,
    currentChapter = null,
    currentAnnotation = null,
    chapters = [],
    annotations = [];

$(function(){

var global = {
    colorsIndex : 0,
    colors : 
        ['#f39c12', '#2ecc71', '#3498db', '#9b59b6',  
        '#f1c40f', '#e67e22', '#e74c3c', 
        '#16a085', '#27ae60', '#2980b9', '#8e44ad', 
         '#d35400', '#c0392b', '#bdc3c7']
};


//position de la video setCurrentTime
$(".indicateur-annotation").draggable({
    axis: "x",
    containment: "parent",
    drag: function(e, ui) {
        var t = myMedia.duration * parseInt(ui.helper.css("left")) / ( $(".timeline-annotations").width() - 2 * ui.helper.width() );
        myMedia.setCurrentTime(t);
    }
});

$('.timeline-annotations').bind('click', function(e){
    var x = e.pageX - $(this).offset().left;
    myMedia.setCurrentTime(myMedia.duration * x / $(this).width());
});

myProject.onLoad(function() {

    $(".project-title").text(myProject.title);
    $('.project-title-nav').text(myProject.title);

    myMedia = myProject.getCurrentMedia();

//load Chapitre
var _chapters = myProject.getAnnotationsByTypeTitle("chapitrage");
if(_chapters.length){
    $.each(_chapters, function(k, v){
        v.color = getRandomColor();
        chapters.push(v);
        if((k+1) == _chapters.length){
            renderChapter();
        }
    });
}

//load Annotations
var _annotations = myProject.getAnnotationsByTypeTitle("annotations");
if(_annotations.length){
    $.each(_annotations, function(k, v){

        v.color = getRandomColor();
        var type = v.content.mimetype.split('-');
        type = type[type.length-1]
        v.type = type;

        annotations.push(v);
        if((k+1) == _annotations.length){
            renderAnnotation();
        }

    });
}

    IriSP.htmlPlayer(
        myMedia,
        $(".main-video"),
        {
            width: 460,
            height: 345,
            controls: true,
            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) {

        //curseur chapitre
        var wContainer = $('.chapitre-cut-wrap').width() - 1,
            pos = wContainer * t / myMedia.duration,
            btnCutChapter = $('.btn-cut-chapter'),
            wBtnCutChapter = btnCutChapter.outerWidth();
        
        $(".indicateur-chapter, .indicateur-annotation").css("left",pos);
        if(pos+wBtnCutChapter>wContainer){
            btnCutChapter.css("left",(pos - wBtnCutChapter));
        }else{
            btnCutChapter.css("left",pos);
        }

        //annotations view
        var currentAnnotationsDisplay = new Array();
        $.each(annotations, function(k, v){

            if(v.begin <= t && v.end >= t){
                currentAnnotationsDisplay.push(v.id);
                if(!$('#item-current-annotation-'+v.id).length){
                    var itemAnnotation = 
                        $('<li>')
                            .attr('id', 'item-current-annotation-'+v.id)
                            .attr('data-id', v.id)
                            .append(
                                $('<a>')
                                    .css('backgroundColor', v.color)
                                    .attr('data-id', v.id)
                                    .attr('href', '#')
                                    .append(
                                        $('<i>').addClass('icon-'+getIcon(v.type))
                                    )
                            );
                    $('.list-current-annotations').append(itemAnnotation)
                }
            }
        });
        $.each($('.list-current-annotations li'), function(k, v){
            var idAnnotation = $(this).attr('data-id'),
                annotationDisplayView = $('.annotation-display-view');
            if($.inArray(idAnnotation, currentAnnotationsDisplay)<0){//il ne doit plus être affiché
                $('#item-current-annotation-'+idAnnotation).remove();
                if(annotationDisplayView.attr('data-id') == idAnnotation && annotationDisplayView.is(":visible")){
                    annotationDisplayView.hide();
                }
            }
        });


    });//timeupdate
    
});//myProject.onLoad

//display annotation view
$('.list-current-annotations').on('click', 'a', function(e){
    e.preventDefault();
    var annotationDisplayView = $('.annotation-display-view'),
        idAnnotation = $(this).attr('data-id');
    var annotation = _.find(annotations, function(c){ return c.id == idAnnotation; });

    if(annotationDisplayView.attr('data-id') == idAnnotation && annotationDisplayView.is(":visible")){
        annotationDisplayView.hide();
    }else{
        annotationDisplayView
            .attr('data-id', idAnnotation)
            .css('backgroundColor', annotation.color)
            .text(annotation.type)
            .show();
    }
});

//########### modal

    $(document).on('click', 'a.open-modal', function(e){

    });

//edition image
    $('.popup').on('change', '#media-type-select', function(e){
        var typeImage = $(this).val();
        $('.input-image-url, .input-image-upload').hide();
        $('.input-image-'+typeImage).show();
    });

//select on bibliotheque

    
    

    //confirmation suppression
    $("#modal-confirm").on('click', '#btn-delete-modal', function(e){
        
        var typeDelete = $(this).attr('data-type-delete'),
            idAnnotation = $(this).attr('data-id');

        if(typeDelete == 'chapter' || typeDelete == 'annotation'){
            e.preventDefault();
            if(typeDelete == 'chapter') deleteChapter(idAnnotation);
            if(typeDelete == 'annotation') deleteAnnotation(idAnnotation);
        }
    });

//--apercu projet
$(document).on('click', '.btn-apercu-projet.disabled', function(e){
    e.preventDefault();
});

//--title-editor
    $(document).on('click', '.project-title-editor i, .project-title', function () {
        var html = $('.project-title').html();
        var input = $('<input type="text" />');
        input.val(html);
        $('.project-title').replaceWith(input);
        input.focus();
    });
    $(document).on('blur', '.project-title-editor input', function(){
        var newTitle = $(this).val();
        myProject.title = newTitle;
        $(this).replaceWith('<span class="project-title">'+newTitle+'</span></td>');
        $('.project-title-nav').text(newTitle);
    });


//######################## chapter

//edit
    $('.list-chapter-wrap').on('click', '.btn-edit-chapter', function(e){
        e.preventDefault();
        var idChapter = $(this).attr('data-chapter-id');
        loadFormChapter(idChapter);
    });

    $('.chapter-segments').on('click', 'li', function(){
        var idChapter = $(this).attr('id');
        loadFormChapter(idChapter);
    });

    $('.chapter-widget-info').on('keyup', 'input[name=title], textarea', function(e){
        var name = $(this).attr('name'),
            value = $(this).val();
        currentChapter[name] = value;
        if(name == 'title'){
            var idChapter = $(this).parents('form').attr('data-chapter-id');
            $('.chapter-segments').find('#'+idChapter).text(value);
            $('#row-list-chapter-'+idChapter).find('td:first').text(value);
        }
    });



    function loadFormChapter(idChapter){

        

        currentChapter = _.find(chapters, function(c){ return c.id == idChapter; });
        var chapterWrap = $('.chapter-widget-info'),
            indexChapter = _.indexOf(chapters, currentChapter),
            beginTangle = (indexChapter>0) ? true : false,
            endTangle = (indexChapter<(chapters.length-1)) ? true : false;

        currentChapter.beginTangle = beginTangle;
        currentChapter.endTangle = endTangle;

        var tpl = getTemplate('#tpl-chapter-edit');
            tpl = Mustache.render(tpl, currentChapter);
            chapterWrap.empty().append(tpl);
            chapterWrap.find('.tag-it').tagit(tagitParam);

        myMedia.setCurrentTime(currentChapter.begin);
    }

    function getTemplate(idTpl){
        return $('#templates').find(idTpl).html();
    }
//supprimer
$('.list-chapter-wrap').on('click', '.btn-delete-chapter', function(e){
    e.preventDefault();

    if(chapters.length == 1){alert('Le projet doit contenir au moins un chapitre.'); return;}
    var idChapter = $(this).attr('data-chapter-id'),
        btnDeleteModal = $("#modal-confirm #btn-delete-modal");
    btnDeleteModal.attr('data-type-delete', 'chapter');
    btnDeleteModal.attr('data-id', idChapter);
   // $("#modal-confirm #btn-delete-modal").attr('onclick', 'deleteChapter("'+idChapter+'")')
/*
    var idChapter = $(this).attr('data-chapter-id'),
        chapter = _.find(chapters, function(c){ return c.id == idChapter; }),
        indexChapter = _.indexOf(chapters, chapter),
        chapterModify;
    if(indexChapter == 0){
        chapterModify = chapters[1];
        chapterModify.setBegin(0);
    }else{
        chapterModify = chapters[indexChapter-1];
        //var newEnd = new IriSP.Model.Time(chapter.end)
        chapterModify.setEnd(chapter.end);
    }
    chapters = _(chapters).reject(function(c) { return c.id == idChapter; });
    renderChapter();
    //si le formulaire est visible
    if($('#form-chapter-edit-'+idChapter).length){
        $('#form-chapter-edit-'+idChapter).remove();
    }
*/

});

function deleteChapter(idChapter){
    $("#modal-confirm").modal('hide')
    var chapter = _.find(chapters, function(c){ return c.id == idChapter; }),
        indexChapter = _.indexOf(chapters, chapter),
        chapterModify;
    if(indexChapter == 0){
        chapterModify = chapters[1];
        chapterModify.setBegin(0);
    }else{
        chapterModify = chapters[indexChapter-1];
        //var newEnd = new IriSP.Model.Time(chapter.end)
        chapterModify.setEnd(chapter.end);
    }
    chapters = _(chapters).reject(function(c) { return c.id == idChapter; });
    renderChapter();
    //si le formulaire est visible
    if($('#form-chapter-edit-'+idChapter).length){
        $('#form-chapter-edit-'+idChapter).remove();
    }
}

function getRandomColor(){
    return global.colors[(global.colorsIndex<global.colors.length) ? global.colorsIndex++ : (global.colorsIndex=0)];
}
//nouveau chapitre
    function newChapter(dataChapter, render){
        var chapter = new IriSP.Model.Annotation(false, myProject);
            chapter.setMedia(myMedia.id);
            chapter.setBegin(dataChapter.begin);
            chapter.setEnd(dataChapter.end);
            chapter.title = dataChapter.title;
            chapter.description = dataChapter.description;
            chapter.keywords = dataChapter.keywords;
            chapter.color = getRandomColor();
    
        chapters.push(chapter);
        renderChapter();
        loadFormChapter(chapter.id);
    }

    $('.chapter-widget').on('click', '.btn-cut-chapter', function(e){
        e.preventDefault();

        var dataChapter = {
                title : 'New',
                begin : myMedia.currentTime,
                end : organizeNewChapter(myMedia.currentTime),
                description : 'description',
                keywords : ['tag1','tag2']
            };

        newChapter(dataChapter, true);

    });
    
    function organizeNewChapter(beginNew){

        var returnEnd;
        $.each(chapters, function(k, v){
            var begin = v.begin,
                end = v.end;
            if(beginNew>=begin && beginNew<=end){
                returnEnd = new IriSP.Model.Time(end);
                v.setEnd(beginNew); 
            }
        });
 
        return returnEnd;
    }
    
    function renderChapter(){
        var chapterSegmentWrap = $('.chapter-segments'),
            wChapterSegmentWrap = chapterSegmentWrap.width(),
            chapterList = $('.list-chapter-rows-wrap');

        chapters = _.sortBy(chapters, function(c){
            return c.begin;
        });

        chapterSegmentWrap.empty();
        chapterList.empty();
       
            $.each(chapters, function(k, v){

                //segments
                var width = v.getDuration() * wChapterSegmentWrap / myMedia.duration,
                    left = v.begin * wChapterSegmentWrap / myMedia.duration,
                    segment = $('<li>'+v.title+'</li>').css({
                        left : left,
                        width : width,
                        backgroundColor : v.color
                    }).attr('id', v.id);
        
                chapterSegmentWrap.append(segment);

                //liste
                var tplChapterRow = getTemplate('#tpl-chapter-row');
                tplChapterRow = Mustache.render(tplChapterRow, v);
                chapterList.append(tplChapterRow);
            });
     
    }//renderChapter()



//######################## annotation
    

    function newAnnotation(dataAnnotation){
        var annotation = new IriSP.Model.Annotation(false, myProject);
            annotation.setMedia(myMedia.id);
            annotation.setBegin(dataAnnotation.begin);
            annotation.setEnd(dataAnnotation.end);
            annotation.title = dataAnnotation.title;
            annotation.description = dataAnnotation.description;
            annotation.type = dataAnnotation.type;
            annotation.color = global.colors[(global.colorsIndex<global.colors.length) ? global.colorsIndex++ : (global.colorsIndex=0)];
            annotation.keywords = dataAnnotation.keywords;
            annotation.content = getContentAnnotationByType(dataAnnotation.type);

        annotations.push(annotation);
        
        return annotation;
    }

    function renderAnnotation(){
        var timeline = $('.timeline-annotations'),
            wTimeline = timeline.width(),
            annotationList = $('#list-annotations-rows');

        annotations = _.sortBy(annotations, function(c){
            return c.begin;
        });

        timeline.empty().append('<li>');
        annotationList.empty();

        $.each(annotations, function(k, v){

            //timeline
            var width = Math.floor(v.getDuration() * wTimeline / myMedia.duration),
                left = Math.floor(v.begin * wTimeline / myMedia.duration),
                segment = $('<div>').css({
                    left : left,
                    width : width,
                    backgroundColor : v.color
                }).addClass('annotation').attr('id', 'annotation-timeline-'+v.id);

            var isInTimeline = false;
            $.each(timeline.find('li'), function(a, b){
                if(isInTimeline) return;
                var row = $(this);
                if(row.children().length){
                    var canBeInRow = true;
                    $.each(row.find('.annotation'), function(c, d){
                        var oAL = parseInt($(d).css('left')),
                            oAR = oAL + $(d).width(),
                            segmentR = left + width;
                        if(oAL<=left && oAR>=left || oAL<=segmentR && oAR>= segmentR){
                            canBeInRow = false;
                        }
                    });
                    if(canBeInRow){
                        row.append(segment);
                        isInTimeline = true;
                    }
                }else{
                    row.append(segment);
                    isInTimeline = true;
                }
            });

            if(!isInTimeline){
                timeline.append('<li>');
                timeline.find('li:last-child').append(segment);
            }
            
           
            //liste
                v.iconTab = getIcon(v.type);
                var tplAnnotationRow = getTemplate('#tpl-list-annotation-row');
                tplAnnotationRow = Mustache.render(tplAnnotationRow, v);
                annotationList.append(tplAnnotationRow);

        });


    }//renderAnnotation

    //edit annotation
    $('#list-annotations').on('click', 'a.btn-edit-annotation', function(e){
        e.preventDefault();

        var idAnnotation = $(this).attr('data-id');
        //si il est déjà ouvert
        if($('#tab-annotation-'+idAnnotation).length){
            $('a[href=#tab-annotation-'+idAnnotation+']').tab('show');
        }else{
            var data = _.find(annotations, function(c){ return c.id == idAnnotation; });
            openTab(data.type, data);
        } 
    });

    $('.tab-content').on('keyup', 'input[name=title], textarea', function(e){
        var name = $(this).attr('name'),
            value = $(this).val();
        currentAnnotation[name] = value;
        if(name == 'title'){
            var idAnnotation = $(this).parents('form').attr('data-id');
            $('#onglet-title-'+idAnnotation).text(value);
        }
    });

    //delete annotation
    $(document).on('click','.btn-delete-annotation', function(e){
        e.preventDefault();
        /*
        var idAnnotation = $(this).attr('data-id');
        annotations = _(annotations).reject(function(c) { return c.id == idAnnotation; });
        closeTab(idAnnotation);
        if(!$(this).hasAttr('data-no-render'))//si on ferme à partir de la tab renderAnnotation sera appelé 2 fois
            renderAnnotation();
        */
        var idAnnotation = $(this).attr('data-id'),
            btnDeleteModal = $("#modal-confirm #btn-delete-modal");
        btnDeleteModal.attr('data-type-delete', 'annotation');
        btnDeleteModal.attr('data-id', idAnnotation);
    });

    function deleteAnnotation(idAnnotation){
        $("#modal-confirm").modal('hide');
        annotations = _(annotations).reject(function(c) { return c.id == idAnnotation; });
        closeTab(idAnnotation);
        renderAnnotation();
    }

//tab
    $('#onglet-annotations').on('click', 'a', function(e){
        e.preventDefault();
        $(this).tab('show');
    });

    //ouvrir tab
    $(document).on('click', '.open-tab', function(e){
        e.preventDefault();
        var type = $(this).attr('data-type');
        openTab(type);
    });

    function openTab(type, data){
        
        var dataView;
        if(_.isUndefined(data)){//nouveau
            var currentTimePlusUnMin = 60 * 1000 + myMedia.currentTime,
                endAnnotation = (currentTimePlusUnMin<myMedia.duration) ? currentTimePlusUnMin : myMedia.duration;
            var dataAnnotation = {
                title : '',
                begin : myMedia.currentTime,
                end : endAnnotation,
                description : '',
                type : type,
                keywords : []
            };
            dataView = newAnnotation(dataAnnotation);
            renderAnnotation();
        }else{//édition
            dataView = data;
        }

        var idAnnotation = dataView.id,
            tabContent = $('<div class="tab-pane" id="tab-annotation-'+idAnnotation+'"></div>'),
            iconTab;

        currentAnnotation = _.find(annotations, function(c){ return c.id == idAnnotation; });

      

            //head commun à tous
            var tplHead = getTemplate('#tpl-head');
            var output = Mustache.render(tplHead, dataView);
            $(tabContent).append(output);
            $(tabContent).find(".slider-duration").slider(configSlider(dataView));
            $(tabContent).find('.tag-it').tagit(tagitParam);
            //type
            var viewType = {
                id : idAnnotation,
                content : dataView.content
            };
            var tpl = getTemplate('#tpl-'+type);

            tpl = Mustache.render(tpl, viewType);
            $(tabContent).append(tpl);
            $('.tab-content').append(tabContent);

            //particularité selon type
            switch(type){
                case 'audio':
                    break;
                case 'video':
                    
                    if(viewType.content.url != ""){

                        var videoWrap = $(tabContent).find('.annotation-video-content');
                        renderVideoInfo(videoWrap, viewType.content);
   
                    }

                    

                    break;
                case 'text': 
                    var cledit = $(tabContent).find('.wysiwyg').cleditor(wysiwygConfig)[0];
                    break;
                case 'links': 
                    var tbody = $(tabContent).find('tbody.links-rows'),
                        links = viewType.content.links;
                    if(links.length){
                        $.each(links, function(k,v){
                            addLinkRow(tbody, v);
                        });
                    }else{//il n'y a pas de lien on en ajoute 1
                        addLinkRow(tbody);
                    }
                    break;

                case 'slideshow': 

                    $(tabContent).find('.number-spin').spin(spinParam);
                    $(tabContent).find('.ui-sortable').sortable({
                        start: function (event, ui) {
                            $(ui.item).data("startindex", ui.item.index());
                        },
                        stop : function(event, ui){
                            disabledBtnSortable($(this));
                        },
                        update : function(event, ui){
                            var oldIndex = ui.item.data("startindex"),
                                newIndex = ui.item.index();
                            currentAnnotation.content.images.move(oldIndex, newIndex);
                        },
                    });
                    var diaporama = $(tabContent).find('#diaporama-'+idAnnotation),
                        images = viewType.content.images;
                    if(images.length){
                        $.each(images, function(k,v){
                            addImageToDiaporama(diaporama, v);
                        });
                    }
                    break;
            }

            dataView.iconTab = getIcon(type);
            var tplOnglet = getTemplate('#tpl-onglet');
            var onglet = Mustache.render(tplOnglet, dataView);

            $(".nav-tabs li:last-child").after(onglet);
            $('a[href=#tab-annotation-'+idAnnotation+']').tab('show');
  
    }//openTab()

    function getIcon(type){
        var icon;
        switch(type){
            case 'audio': icon = 'volume-up';
                break;
            case 'video': icon = 'film';
                break;
            case 'text': icon = 'align-left';
                break;
            case 'html': icon = 'code';
                break;
            case 'links': icon = 'link';
                break;
            case 'slideshow': icon = 'picture';
                break;
        }
        return icon;
    }

    //définit currentAnnotation quand la tab s'ouvre
    $('#onglet-annotations').on('show', 'a[data-toggle="annotation"]', function (e) {
        var idAnnotation = $(e.target).attr('data-id');
        currentAnnotation = _.find(annotations, function(c){ return c.id == idAnnotation; });
    });

    //rafraichit annotations au retour sur la liste
    $('#onglet-annotations').on('show', 'a[data-toggle="list-annotations"]', function (e) {
        renderAnnotation();
    });

    //fermer tab
    $('#onglet-annotations').on('click', 'span.close-tab', function(e){
        e.preventDefault();e.stopPropagation();
        var idAnnotation = $(this).parents('a').attr('data-id');
        closeTab(idAnnotation);
    });

    $('.tab-content').on('click', '.btn-save-annotation', function(e){
        e.preventDefault();
        var idAnnotation = $(this).attr('data-id');
        closeTab(idAnnotation);
    });

    function closeTab(idAnnotation){
        $('#onglet-'+idAnnotation).remove();
        $('.tab-content #tab-annotation-'+idAnnotation).remove();
        $('#tab-list-annotation').tab('show');
    }

//video
    function renderVideoInfo(videoWrap, dataVideo){
    
        var tplVideo = getTemplate('#tpl-video-row');
        tplVideo = Mustache.render(tplVideo, dataVideo);
        
        videoWrap.empty().append(tplVideo);

        videoWrap = videoWrap.find(".video-container");
        getVideoPlayer(dataVideo.url, videoWrap);
     
    }
    $('.popup').on('click', '.bibliotheque-video a', function(e){
        e.preventDefault();

        var url = $(this).attr('data-url'),
            title = $(this).attr('data-title'),
            description = $(this).attr('data-description');

        currentAnnotation.content.url = url;
        currentAnnotation.content.title = title;
        currentAnnotation.content.description = description;

        $('.popup').modal('hide');

        var videoWrap = $('#tab-annotation-'+currentAnnotation.id).find('.annotation-video-content');
        renderVideoInfo(videoWrap, currentAnnotation.content);

        
    });

//diaporama

    //bibliotheque
    $('.popup').on('click', '.bibliotheque-image a', function(e){
        e.preventDefault();

        var url = $(this).attr('data-url'),
            title = $(this).attr('data-title'),
            description = $(this).attr('data-description'),
            image = {
                id : currentAnnotation.id,
                url : url,
                title : title,
                description : description
            };
        currentAnnotation.content.images.push(image);

        var listDiaporama = $('#diaporama-'+currentAnnotation.id);
        addImageToDiaporama(listDiaporama, image);
        $('.popup').modal('hide'); 
    });

    function addImageToDiaporama(diaporama, dataView){
   
        var tplDiapo = getTemplate('#tpl-diaporama-row');
        tplDiapo = Mustache.render(tplDiapo, dataView);
        diaporama.append(tplDiapo);
        disabledBtnSortable(diaporama);
    
    };

    //bouton up / down
    $(document).on('click', '.ui-sortable .btn-sort', function(e){
        e.preventDefault();
        var row = $(this).parents('tr.row-image-diaporama'),
            oldIndex = row.index(),
            listDiaporama = $(this).parents('.list-image-diaporama');

        if($(this).hasClass('down'))
            row.insertAfter(row.next());
        else if($(this).hasClass('up'))
            row.insertBefore(row.prev());

        var newIndex = row.index();
        currentAnnotation.content.images.move(oldIndex, newIndex);

        disabledBtnSortable(listDiaporama);
    });

    $('.tab-content').on('click','.btn-delete-image', function(e){
        e.preventDefault();
        var rowImage = $(this).parents('tr.row-image-diaporama'),
            index = rowImage.index();

        rowImage.remove();
        currentAnnotation.content.images.splice(index, 1);
    });

    function disabledBtnSortable(listDiaporama){
        listDiaporama.find('.btn-sort.disabled').removeClass('disabled');
        listDiaporama.find('tr.row-image-diaporama:first-child').find('.btn-sort.up').addClass('disabled');
        listDiaporama.find('tr.row-image-diaporama:last-child').find('.btn-sort.down').addClass('disabled');
    }

    
//links
$('.tab-content').on('click', '.add-link', function(e){
    e.preventDefault();
    var tbody = $(this).parents('tfoot').siblings('tbody');
    addLinkRow(tbody);
});
$('.tab-content').on('click', '.delete-link', function(e){
    e.preventDefault();
    var row = $(this).parents('tr'),
        tbody = $(this).parents('tbody');

    row.remove();
    updateLinks(tbody);
});
function addLinkRow(tbody, dataView){

        //head commun à tous
        var tplLinkRow = getTemplate('#tpl-links-row');
        var output = Mustache.render(tplLinkRow, dataView);
        tbody.append(output);

}
$('.tab-content').on('keyup', '.links-rows input', function(e){
    var tbody = $(this).parents('.links-rows');
    updateLinks(tbody);   
});
function updateLinks(tbody){
    links = new Array();

    $.each(tbody.find('tr'), function(k, v){
        var urlLink = $(v).find('.url-link').val(),
            titleLink = $(v).find('.title-link').val(),
            link = {
                url : urlLink,
                title : titleLink
            };
            links.push(link);

    });
    currentAnnotation.content.links = links;
}

//annotation audio
$('.tab-content').on('keyup', '.annotation-audio-content input, .annotation-audio-content textarea', function(){
    var name = $(this).attr('name'),
        value = $(this).val();

    currentAnnotation.content[name] = value;
});

//annotation slideshow
$('.tab-content').on('click', '.btn-autostart', function(){
    var autostart = $(this).attr('data-autostart');
    if(autostart == "true"){ autostart = true;}
    else {autostart = false;}
    currentAnnotation.content.autostart = autostart;
});

$('.tab-content').on('change keyup', '.config-diaporama input[name=duration]', function(){
    var value = $(this).val();
    if(!isNaN(value)){
        currentAnnotation.content.duration = value;
    }
});

//################ config
//tagit
function onTagItChange(e, ui) {
    var tagitType = $(this).attr('data-type'), 
        value = $(this).val();

    if(tagitType == 'chapter'){
        var idChapter = $(this).parents('form').attr('data-chapter-id');
        currentChapter.keywords = value.split(',');
        $('#row-list-chapter-'+idChapter).find('.list-chapter-tags').text(value);
    }else{
        currentAnnotation.keywords = value.split(',');
    }
    
}

var tagitParam = {
    afterTagRemoved : onTagItChange,
    afterTagAdded : onTagItChange
}

//CLEditor annotation > text (wysiwyg)
//http://premiumsoftware.net/cleditor/docs/GettingStarted.html#optionalParameters
var wysiwygConfig = {
    width:        456, 
    height:       250, 
    controls:     "bold italic underline strikethrough | font size " +
                    "style | color highlight removeformat | bullets numbering | source",
    fonts:        "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," +
                    "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana",
    sizes:        "1,2,3,4,5,6,7",
    styles:       [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
                    ["Header 3", "<h3>"],  ["Header 4","<h4>"],  ["Header 5","<h5>"],
                    ["Header 6","<h6>"]],
    docType:      '<!DOCTYPE HTML>',
    bodyStyle:    "margin:0; font-family: 'Helvetica Neue',​Helvetica,​Arial,​sans-serif;",
    updateTextArea : function(text){
        currentAnnotation.content.text = text;
        return text;
    },
    updateFrame: function(text){
        currentAnnotation.content.text = text;
        return text;
    }
};

//slider
function configSlider(data){
    return {
        range: true,
        values: [ data.begin.milliseconds, data.end.milliseconds ],
        min: 0,
        max: myMedia.duration.milliseconds,
        slide: function( event, ui ) {
            
            data.setBegin(ui.values[0]);
            data.setEnd(ui.values[1]);

            var idSlider = $(this).attr('data-id'),
                wTimeline = $('.timeline-annotations').width(),
                annotationTimeline = $('#annotation-timeline-'+ data.id),
                width = Math.floor(data.getDuration() * wTimeline / myMedia.duration),
                left = Math.floor(data.begin * wTimeline / myMedia.duration);

            $( '#'+ idSlider +'-begin' ).html(data.begin.toString());
            $( '#'+ idSlider +'-duration' ).html(data.getDuration().toString());
            $( '#'+ idSlider +'-end' ).html(data.end.toString());

            annotationTimeline.css({
                left : left,
                width :width
            });
        },
        start : function(){
            var idSlider = $(this).attr('data-id'),
                annotationTimeline = $('#annotation-timeline-'+ data.id);
            annotationTimeline.css('z-index',100);
        },
        stop : function(){
            renderAnnotation()
        }
    };
}

//init annotation content data
function getContentAnnotationByType(type){
    var content;
    switch(type){
        case 'audio':
            content = {
                mimetype : "application/x-ldt-audio",
                url : "",
                embedcode : ""
            };
            break;
        case 'video':
            content = {
                mimetype : "application/x-ldt-video",
                url : "",
                embedcode : ""
            };
            break;
        case 'text': 
            content = {
                mimetype : "application/x-ldt-text",
                markup : "html",
                text : "azerty"
            };
            break;
        case 'links': 
            content = {
                mimetype : "application/x-ldt-links",
                links : []
            };
            break;
        case 'slideshow': 
            content = {
                mimetype : "application/x-ldt-slideshow",
                duration : 1,
                autostart : false,
                images : []
            };
            break;
    }
    return content;
}//getContentAnnotationByType




//test

$('.log-annotations').bind('click', function(e){
    e.preventDefault();
    console.log(annotations.length + ' annotations', annotations);
});

$('.log-chapters').bind('click', function(e){
    e.preventDefault();
    console.log(chapters.length + ' chapitres',chapters);
});

});//ready

//Utilitaires
Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this; 
};


function getVideoPlayer(src, videoWrap){

    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 = 460,
        mediaH = 345,
        autoplay = false;

    
    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];
        }
        videoWrap.html(youtubeTemplate({
            ytid: ytid,
            width: mediaW,
            height: mediaH,
            autoplay: autoplay
        }));
        return;
    }
    
    if (/^(https?:\/\/)?(www\.)?vimeo/.test(src)) {
        $.ajax({
            url: "http://vimeo.com/api/oembed.json",
            dataType: "jsonp",
            data: {
                width: mediaW,
                height: mediaH,
                url: src,
                autoplay: autoplay,
                color: "be4477",
                portrait: false,
                title: false,
                byline: false
            },
            success: function(data) {
                videoWrap.html(data.html);
            }
        });
        return;
    }
    
    if (/^(https?:\/\/)?(www\.)?dailymotion/.test(src)) {
        $.ajax({
            url: "http://www.dailymotion.com/services/oembed",
            dataType: "jsonp",
            data: {
                format: "json",
                maxwidth: mediaW,
                maxheight: mediaH,
                url: src
            },
            success: function(data) {
                videoWrap.html(data.html);
            }
        });
        return;
    }
    
    if (/^(https?:\/\/)?(www\.)?soundcloud\.com/.test(src)) {
        $.ajax({
            url: "http://soundcloud.com/oembed",
            dataType: "jsonp",
            data: {
                format: "js",
                show_comments: false,
                auto_play: autoplay,
                show_artwork: false,
                url: src,
                color: "63be6c"
            },
            success: function(data) {
                videoWrap.html(data.html);
            }
        });
        return;
    }
    
    var extension = (src.match(/\.([\d\w]+)$/) || ["",""])[1],
        mimetype = 'video' + "/" + extension,
        fallbacks = { "video/webm": "mp4", "video/mp4": "webm" },
        canPlay = document.createElement("video").canPlayType(mimetype);
    
    if (!canPlay) {
        src = src.replace(/\.[\d\w]+$/,"." + fallbacks[mimetype]);
    }
    
    console.log(mimetype, canPlay, src);
    
    videoWrap.html(htmlTemplate({
        type: 'video',
        src: src,
        width: mediaW,
        height: mediaH,
        autoplay: "" + autoplay
    }));
                
}//getVideoPlayer