integration/js/edition.js
author Anthony Ly <anthonyly.com@gmail.com>
Mon, 27 May 2013 15:24:46 +0200
changeset 38 0e6e631718ee
parent 36 4c2428524c22
child 42 95e64fb6730f
permissions -rw-r--r--
scrollbar modal

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

$(function(){

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


myProject.onLoad(function() {

    $(".project-title").text(myProject.title);
    
    myMedia = myProject.getCurrentMedia();
    
    //chargement des chapitres et annotations existants
    loadInitChapters();
    loadInitAnnotation()

    IriSP.htmlPlayer(
        myMedia,
        $(".main-video"),
        {
            width: 460,
            height: 345,
            controls: true,
            autostart: true
        }
    );

    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){
        var diaporama = $(this).attr('data-diaporama'),
            idAnnotation = $(this).attr('data-id');

        if(diaporama !== undefined){
            global.diaporama = diaporama;
        }
        if(idAnnotation !== undefined){
            global.idAnnotation = idAnnotation;
        }
    });

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

//bibliotheque
    //video
    $('.popup').on('click', '.bibliotheque-video a', function(e){
        e.preventDefault();
        $('.popup').modal('hide');
        $.get('template.html', function(templates){
            var videoWrap = $('#tab-'+global.idAnnotation).find('.annotation-video-content'),
                tplVideo = $(templates).filter('#tpl-video-row').html();
                console.log(videoWrap)
            videoWrap.empty().append(tplVideo);
        });
        
    });
    //image
    $('.popup').on('click', '.bibliotheque-image a', function(e){
        e.preventDefault();
        var listDiaporama = $('#'+global.diaporama);
        addImageToDiaporama(listDiaporama);
        $('.popup').modal('hide');
    });

    

    //confirmation suppression
    $("#modal-confirm").on('click', '#btn-delete-modal', function(e){

    });

//--title-editor
$('.project-title-editor ._popover').bind('click',function(e){e.preventDefault()});
    $('.project-title-editor ._popover').popover({
        html : true,
        content : function(){
            var previousValue = $('.project-title').text(),
                formInput = 
                    '<form action="#" class="project-title-editor-form">'+
                        '<input type="text" class="project-title-editor-input" value="'+previousValue+'">'+
                    '</form>';
            return formInput;
        }
    });

    $('body').on('click', function (e) {
        $('._popover').each(function () {
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });

    $('body').on('submit', '.project-title-editor-form', function(e){
        e.preventDefault();
        $('._popover').popover('hide');
    });

    $(document).on('keyup', '.project-title-editor-input', function() {
        $('.project-title').html($(this).val());
    });

//######################## 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;

        $.get('template.html', function(templates){
            var tpl = $(templates).filter('#tpl-chapter-edit').html();
            tpl = Mustache.render(tpl, currentChapter);
            chapterWrap.empty().append(tpl);
            chapterWrap.find('.tag-it').tagit(tagitParam);
        });
    }


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

//nouveau chapitre
    function newChapter(dataChapter){
        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 = global.colors[(global.colorsIndex<global.colors.length) ? global.colorsIndex++ : (global.colorsIndex=0)];
    
        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);

    });
    
    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){
            //form
            if($('#form-chapter-edit-'+v.id).length){
                loadFormChapter(v.id);
            }
            //segments
            var width = Math.floor(v.getDuration() * wChapterSegmentWrap / myMedia.duration),
                segment = $('<li>'+v.title+'</li>').css({
                    width : width,
                    backgroundColor : v.color
                }).attr('id', v.id);
    
            chapterSegmentWrap.append(segment);

            //liste
            $.get('template.html', function(templates){
                var tplChapterRow = $(templates).filter('#tpl-chapter-row').html();
                tplChapterRow = Mustache.render(tplChapterRow, v);
                chapterList.append(tplChapterRow);

            });
        });
    }

//init
    function loadInitChapters(){//nouveau projet, 1 chapitre
        var dataChapter = {
                title : 'New',
                begin : 0,
                end : myMedia.duration,
                description : 'description',
                keywords : ['tag1','tag2']
            };

        newChapter(dataChapter);
    }


//######################## annotation
    
    function loadInitAnnotation(){//nouveau projet, 1 chapitre
        var dataAnnotation = {
                title : 'Titre azerty',
                begin : myMedia.duration/5,
                end : myMedia.duration/3,
                description : 'description',
                type : 'video',
                keywords : ['ideal', 'tag']
            };

        newAnnotation(dataAnnotation);
        renderAnnotation();
    }

    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;

        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();
        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);
    
            timeline.append(segment);
           
            //liste
            $.get('template.html', function(templates){
                var tplAnnotationRow = $(templates).filter('#tpl-list-annotation-row').html();
                tplAnnotationRow = Mustache.render(tplAnnotationRow, v);
                annotationList.append(tplAnnotationRow);

            });

        });
    }

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

    });

//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 : 'Nouveau',
                begin : myMedia.currentTime,
                end : endAnnotation,
                description : '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; });

        $.get('template.html', function(templates){
            //head commun à tous
            var tplHead = $(templates).filter('#tpl-head').html();
            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};
            var tpl = $(templates).filter('#tpl-'+type).html();
            tpl = Mustache.render(tpl, viewType);
            $(tabContent).append(tpl);
            $('.tab-content').append(tabContent);

            //particularité selon type
            switch(type){
                case 'son':
                    break;
                case 'video':
                    break;
                case 'text': 
                    var cledit = $(tabContent).find('.wysiwyg').cleditor(wysiwygConfig)[0];

                    break;
                case 'html': 
                    break;
                case 'lien': 
                    break;
                case 'diaporama': 
                    $(tabContent).find('.number-spin').spin(spinParam);
                    $(tabContent).find('.ui-sortable').sortable({
                        stop : function(event, ui){
                            disabledBtnSortable($(this));
                        }
                    });
                    break;
            }

            dataView.iconTab = getIcon(type);
            var tplOnglet = $(templates).filter('#tpl-onglet').html();
            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 'son': icon = 'volume-up';
                break;
            case 'video': icon = 'film';
                break;
            case 'text': 
                icon = 'align-left';
                break;
            case 'html': icon = 'code';
                break;
            case 'lien': icon = 'link';
                break;
            case 'diaporama': 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');
    }

//diaporama
    function addImageToDiaporama(diaporama){
        $.get('template.html', function(templates){
            var tplDiapo = $(templates).filter('#tpl-diaporama-row').html(),
                uniqId = 'id' + (new Date()).getTime(),
                viewDiapo = { ridid : uniqId};
            tplDiapo = Mustache.render(tplDiapo, viewDiapo);
            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'),
            listDiaporama = $(this).parents('.list-image-diaporama');

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

        disabledBtnSortable(listDiaporama);
    });

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

    



//annotation html
$('.tab-content').on('click', '.btn-html-apercu', function(e){
    e.preventDefault();

    var apercuWrap = $(this).parents('.edit-annotation-html').find('.html-apercu'),
        htmlTextarea = $(this).parents('.edit-annotation-html').find('textarea');

    apercuWrap.empty().html(htmlTextarea.val());
});

//annotation texte
$(document).on('keyup', ".cleditorMain iframe", function(){

    var v = $(this).text(); // or .html() if desired
    $('#x').html(v);
});
//annotation > diaporama (spin)


//################ 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){

        return text;
    },
    updateFrame: function(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
            });

        }
    };

}

//content annotations
var contentAnnotationText = {
    mimetype : "application/x-ldt-text",
    markup : "html",
    text : ""
};

var contentAnnotationLinks = {
    mimetype : "application/x-ldt-links",
    markup : "html",
    links : []
};

var contentAnnotationVideo = {
    mimetype : "application/x-ldt-video",
    url : "",
    embedcode : ""
};

var contentAnnotationSon = {
    mimetype : "application/x-ldt-sound",
    url : "",
    embedcode : ""
};

var contentAnnotationDiaporama = {
    mimetype : "application/x-ldt-slideshow",
    duration : 1,
    autostart : false,
    images : []
};

//test
a = $(".wysiwyg").cleditor(wysiwygConfig);


$('.number-spin').spin(spinParam);

disabledBtnSortable($('.ui-sortable'))
$('.ui-sortable').sortable({
    stop : function(event, ui){
        disabledBtnSortable($(this));
    }
});

$('.slider-duration').slider(configSlider);

$(".tag-it").tagit();

});//ready