integration/js/edition.js
author Anthony Ly <anthonyly.com@gmail.com>
Fri, 17 May 2013 12:41:30 +0200
changeset 21 abd04f346dbe
parent 18 16b482c153fd
child 22 0e02c3a28491
permissions -rw-r--r--
delete row on enter key press in modal

$(function(){

var global = {
    diaporama : null,
    idAnnotation : null,
    beginCurrentChapter : 0,
    mediaDuration : 0,
    colors : ['#1abc9c', '#3498db', '#9b59b6', '#f1c40f', '#e67e22', '#e74c3c']
},
chapters = [],
annotations = [];

myProject.onLoad(function() {

    $(".project-title").text(myProject.title);
    
    myMedia = myProject.getCurrentMedia();
    
    loadChapters();

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

    myMedia.on("timeupdate", function(t) {

        //init
        global.mediaDuration = myMedia.duration.milliseconds;

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

        //chapitre edit
        var formChapter = $('.form-chapter-edit'),
            inputBeginChapter = formChapter.find('input[name=begin]'),
            inputDurationChapter = formChapter.find('input[name=duration]'),
            inputEndChapter = formChapter.find('input[name=end]'),
            viewBeginChapter = formChapter.find('.begin'),
            viewDurationChapter = formChapter.find('.duration'),
            viewEndChapter = formChapter.find('.end'),
            timeBegin = global.beginCurrentChapter,
            timeEnd = t.milliseconds,
            timeDuration = timeEnd - timeBegin;

        inputBeginChapter.val(timeBegin);
        inputEndChapter.val(timeEnd);
        inputDurationChapter.val(timeDuration);
        viewBeginChapter.html(millisecondsToString(timeBegin));
        viewDurationChapter.html(millisecondsToString(timeDuration));
        viewEndChapter.html(millisecondsToString(timeEnd));
    });//timeupdate
    
});//myProject.onLoad


//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 = $('#'+global.idAnnotation).find('.annotation-video-content'),
                tplVideo = $(templates).filter('#tpl-video-row').html();
            videoWrap.empty().append(tplVideo);
        });
        
    });
    //image
    $('.popup').on('click', '.bibliotheque-image a', function(e){
        e.preventDefault();
        var listDiaporama = $('#'+global.diaporama);
        addImageToDiaporama(listDiaporama);
        $('.popup').modal('hide');
    });

    $(document).on('click','.btn-delete', function(e){
        e.preventDefault();
        //si c'est une annotation et que la tab est ouverte, on la ferme
        var type = $(this).attr('data-type');
        if(type == 'annotation'){
            var idAnnotation = $(this).attr('data-id');
            $('a[href=#annotation-'+idAnnotation+']').closest('li').remove();
            $('.tab-content #annotation'+idAnnotation).remove();
            $('#tab-list-annotation').tab('show');
        }
    });

    //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
    $('.list-chapter-wrap').on('click', '.edit-chapter', function(e){
        e.preventDefault();
        var viewChapter = {
            titre : 'titre du chapitre',
            tags : 'tag 1, tag 2, tag 3',
            description : 'lorem ipsum'
        }
        
        $.get('template.html', function(templates){
            var tpl = $(templates).filter('#tpl-chapter-edit').html();
            var tpl = Mustache.render(tpl, viewChapter);
            $('.form-chapter-edit').empty().append(tpl);
            $('.form-chapter-edit').find('.tag-it').tagit();
        });
    });
    //nouveau chapitre
    $('.chapter-widget').on('click', '.btn-cut-chapter', function(e){
        e.preventDefault();

        var uniqId = 'id' + (new Date()).getTime();
        
        var formChapter = $('.form-chapter-edit'),
            title = formChapter.find('input[name=title]').val(),
            tags = formChapter.find('input[name=tags]').val(),
            begin = formChapter.find('input[name=begin]').val(),
            duration = formChapter.find('input[name=duration]').val(),
            end = formChapter.find('input[name=end]').val(),
            beginString = millisecondsToString(begin),
            durationString = millisecondsToString(duration),
            endString = millisecondsToString(end),
            description = formChapter.find('textarea[name=description]').val(),
            id = uniqId;

        var dataChapter = {
            title : title,
            tags : tags,
            begin : begin,
            duration : duration,
            end : end,
            description : description,
            beginString : beginString,
            durationString : durationString,
            endString : endString,
            id : id
        };

        addChapter(dataChapter);
    });

    function addChapter(dataChapter){
        chapters.push(dataChapter);

        //vue liste chapitre
        $.get('template.html', function(templates){
            var tplChapterRow = $(templates).filter('#tpl-chapter-row').html();
            tplChapterRow = Mustache.render(tplChapterRow, dataChapter);
            $('.list-chapter-rows-wrap').append(tplChapterRow);

            updateChapterSegments();
        });

    }
    
    function updateChapterSegments(){
        var chapterSegmentWrap = $('.chapter-segments'),
            wChapterSegmentWrap = chapterSegmentWrap.width();
        chapterSegmentWrap.empty();

        $.each(chapters, function(k, v){
            var chapter = v,
                color = global.colors[k],
                width = chapter.duration * wChapterSegmentWrap / global.mediaDuration,
                segment = $('<li>'+chapter.title+'</li>').css({
                    width : width,
                    backgroundColor : color
                }).attr('id', chapter.id);
            chapterSegmentWrap.append(segment)
        });
    }

    function loadChapters(){
        //nouveau projet, 1 chapitre
        var uniqId = 'id' + (new Date()).getTime();

        var title = 'chapitre 1',
            tags = 'tag1,tag2',
            begin = 0,
            duration = myMedia.duration.milliseconds,
            end = myMedia.duration.milliseconds,
            beginString = millisecondsToString(begin),
            durationString = millisecondsToString(duration),
            endString = millisecondsToString(end),
            description = 'description du chapitre 1',
            id = uniqId;

        var dataChapter = {
            title : title,
            tags : tags,
            begin : begin,
            duration : duration,
            end : end,
            description : description,
            beginString : beginString,
            durationString : durationString,
            endString : endString,
            id : id
        };

        addChapter(dataChapter);
    }

    //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($('#annotation-'+idAnnotation).length){
            $('a[href=#annotation-'+idAnnotation+']').tab('show');
        }else{
            var typeAnnotation = $(this).attr('data-type'),
                data = {id:idAnnotation};
            openNewTab(typeAnnotation, data);
        } 
    });

//tab
    $('#annotation-tab').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');
        var data = $(this).attr('data-data'); // à définir
        openNewTab(type);
    });

    function openNewTab(type, data){

        var uniqId = 'id' + (new Date()).getTime(),
            idAnnotation = (data !== undefined) ? data.id : uniqId,
            tabContent = $('<div class="tab-pane" id="annotation-'+idAnnotation+'"></div>'),
            iconTab;


        $.get('template.html', function(templates){
            //head commun à tous
            var view = {
                    titre : "un titre mustache",
                    id : uniqId
                };
            var tplHead = $(templates).filter('#tpl-head').html();
            var output = Mustache.render(tplHead, view);
            $(tabContent).append(output);
            $(tabContent).find(".slider-duration").slider(configSlider);

            //type
            var viewType = {id : uniqId};
            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 'video': iconTab = 'film';
                    break;
                case 'text': 
                    iconTab = 'align-left';
                    $(tabContent).find('.wysiwyg').cleditor(wysiwygConfig);
                    break;
                case 'html': iconTab = 'link';
                    break;
                case 'diaporama': iconTab = 'picture';
                    $(tabContent).find('.number-spin').spin(spinParam);
                    $(tabContent).find('.ui-sortable').sortable({
                        stop : function(event, ui){
                            disabledBtnSortable($(this));
                        }
                    });
                    break;
            }
            $(".nav-tabs li:last-child").after('<li><a href="#annotation-'+idAnnotation+'"><i class="icon-'+iconTab+'"></i> New <span class="close-tab">&times;</span></a></li>');
            $('a[href=#annotation-'+idAnnotation+']').tab('show');
        });
    }//openNewTab()

    //fermer tab
    $('#annotation-tab').on('click', 'span.close-tab', function(e){
        e.preventDefault();e.stopPropagation();
        var idTab = $(this).parents('a').attr('href');
        $(this).closest('li').remove();
        $('.tab-content '+idTab).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');
    }

    

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

//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 > diaporama (spin)


//config
//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 | outdent ",
    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;"
};

//slider
var configSlider = {
    range: true,
    values: [ 0, 1*60*1000 ],
    min: 0,
    max: 10*60*1000,
    slide: function( event, ui ) {
        
        var debutString = millisecondsToString(ui.values[0]);
        var endString = millisecondsToString(ui.values[1]);
        var durationString = millisecondsToString(ui.values[1] - ui.values[0]);

        var idSlider = $(this).attr('data-id');
        
        $( '#'+ idSlider +'-begin' ).html(debutString);
        $( '#'+ idSlider +'-duration' ).html(durationString);
        $( '#'+ idSlider +'-end' ).html(endString);
        
    }
};

//milliseconds To 12h12m12s
function millisecondsToString(milliseconds) {
    var oneHour = 3600000;
    var oneMinute = 60000;
    var oneSecond = 1000;
    var seconds = 0;
    var minutes = 0;
    var hours = 0;
    var result;

    if (milliseconds >= oneHour) {
        hours = Math.floor(milliseconds / oneHour);
    }

    milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;

    if (milliseconds >= oneMinute) {
        minutes = Math.floor(milliseconds / oneMinute);
    }

    milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;

    if (milliseconds >= oneSecond) {
        seconds = Math.floor(milliseconds / oneSecond);
    }

    milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;

    if (hours > 0) {
        result = (hours > 9 ? hours : "0" + hours) + "h";
    } else {
        result = "";
    }

    if (minutes > 0) {
        result += (minutes > 9 ? minutes : "0" + minutes) + "m";
    } else {
        result += "00m";
    }

    if (seconds > 0) {
        result += (seconds > 9 ? seconds : "0" + seconds) + "s";
    } else {
        result += "00s";
    }

    return result;
}

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

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

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

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

$('#annotation-tab a:last-child').tab('show');

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

});//ready