(function(){

var _global = {
    diaporama : ''
};

//tab ressources
	$('.tab-behavior a').click(function (e) {
	    e.preventDefault();
	    $(this).tab('show');
    });

//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();
        alert('une vidéo sélectionnée');
        $('.popup').modal('hide');
    });
    //image
    $('.popup').on('click', '.bibliotheque-image a', function(e){
        e.preventDefault();
        alert('une image sélectionnée');
        var listDiaporama = $('#'+_global.diaporama);
        addImageToDiaporama(listDiaporama);
        $('.popup').modal('hide');
    });

    function addImageToDiaporama(diaporama){
        $.get('template.html', function(templates){
            var tplDiapo = $(templates).filter('#tpl-diaporama-row').html();
            diaporama.append(tplDiapo);
            disabledBtnSortable(diaporama);
        });
    };

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

        if(diaporama !== undefined){
            _global.diaporama = diaporama;
        }

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

    });

    $('.btn-delete').bind('click', 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-idEltDelete', eltDelete);
        $("#modal-confirm .modal-body").empty().append(textModal); 
        $("#modal-confirm").modal('show');
    });

    //confirmation suppression
    $("#modal-confirm").on('click', '#btn-delete-modal', function(e){
        e.preventDefault();
        var idEltDelete = $(this).attr('data-idEltDelete');
        $(idEltDelete).remove();
        $("#modal-confirm").modal('hide');
    });

    //ZeroClipboard (fonctionne sous localhost)
    var clip = new ZeroClipboard( $('.clipboard'), {
      moviePath: "js/ZeroClipboard.swf"
    });
    clip.on( 'complete', function(client, args) {
      alert("Copied text to clipboard: " + args.text );
    });

//page edition
//title-editor
    $('.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');
            }
        });
    });

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

    });
//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-idAnnotation');
        //si il est déjà ouvert
        if($(idAnnotation).length){
            $('a[href=#'+idAnnotation+']').tab('show');
        }else{
            var typeAnnotation = $(this).attr('data-type');
            openNewTab(typeAnnotation);
        } */
        var typeAnnotation = $(this).attr('data-type');
            openNewTab(typeAnnotation);
    });

    function openNewTab(type, data){
        var idAnnotation = $(".nav-tabs").children().length,
            tabContent = $('<div class="tab-pane" id="annotation-'+idAnnotation+'"></div>'),
            iconTab;

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

            //type
            var uniqId = 'id' + (new Date()).getTime(),//test
                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()

//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 :'img/spin/',
    max:60,
    min:0
};

//annotation > text (wysiwyg)
//http://premiumsoftware.net/cleditor/docs/GettingStarted.html#optionalParameters
var wysiwygConfig = {
    width:        456, 
    height:       250, 
    controls:     "bold italic underline strikethrough subscript superscript | 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;"
};

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

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

$('.slider-duration').slider({
    range : true
});

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

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

})(jQuery);