(function(){

var global = {
    diaporama : null,
    idAnnotation : null
};

//modal
    $('.popup').on('click', '.popup-content a', function(e){
    	e.preventDefault();
    	if($(this).hasClass('btn-cancel')){
    		$(this).parents('.popup').modal('hide');
    	}
    	if($(this).hasClass('btn-previsualisation')){
    		var imgPrev = $('<img src="img/520x520.gif" alt="" />');
    		$('.previsualisation').empty().append(imgPrev);
    	}
    });
//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();
        var titleMedia = $(this).attr('data-title'),
            textModal = $('<p>Êtes-vous sûr de vouloir supprimer <strong>'+titleMedia+'</strong> ?</p>'),
            eltDelete = $(this).attr('href');
        $("#modal-confirm #btn-delete-modal").attr('data-id-elt-delete', eltDelete);
        $("#modal-confirm .modal-body").empty().append(textModal); 
        $("#modal-confirm").modal('show');

        //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){
        e.preventDefault();
        var idEltDelete = $(this).attr('data-id-elt-delete');
        $(idEltDelete).remove();
        $("#modal-confirm").modal('hide');
    });

    

//page edition

//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);
        });
    });
    //nouveau chapitre
    $('.chapter-widget').on('click', '.btn-cut-chapter', function(e){
        e.preventDefault();
        var uniqId = 'id' + (new Date()).getTime();
        $.get('template.html', function(templates){
            var viewChapterRow = {
                    id : uniqId
                };
            var tpl = $(templates).filter('#tpl-chapter-row').html();
            var tpl = Mustache.render(tpl, viewChapterRow);
            $('.list-chapter-rows-wrap').append(tpl);
        });
    });
//tab
    $('#annotation-tab').on('click', 'a', function(e){
        e.preventDefault();
        $(this).tab('show');
    });
    $('#annotation-tab a:last-child').tab('show');

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

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

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

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

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

    $(document).on('click', 'a.open-modal', function(e){
        e.preventDefault();
        var modalRemote = $(this).attr('href'),
            typeMedia = $(this).attr('data-type-media'),
            modalTitleInfo = $(this).attr('data-title'),
            diaporama = $(this).attr('data-diaporama'),
            idAnnotation = $(this).attr('data-id'),
            titleFront;

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

        switch(typeMedia){
            case 'video' : titleFront = '<i class="icon-film"></i> Vidéo - '+modalTitleInfo; break;
            case 'image' : titleFront = '<i class="icon-picture"></i> Image - '+modalTitleInfo; break;
        }
        $('#modal-template .modal-header h3').html(titleFront);

        $("#modal-template .modal-body").load(modalRemote, function() { 
            $("#modal-template").modal("show"); 
        });

    });

//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)
var spinParam = {
    imageBasePath :'lib/spin/img/',
    max:60,
    min:0
};

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


//test
if($(".wysiwyg").length){
    $(".wysiwyg").cleditor(wysiwygConfig);
}

if($(".number-spin").length){
    $('.number-spin').spin(spinParam);
}


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




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

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";
    }
/*
    if (milliseconds > 0) {
        result += (milliseconds > 9 ? milliseconds : "0" + milliseconds);
    } else {

        result += "00";
    }
*/
    return result;
}
})(jQuery);