$(document).ready(function () {
	
    function enabledFilter(){
        var filter_enabled = false;
        var chbs = $(".spel-content input:checkbox");
        for (var i = chbs.length - 1; i >= 0; i--) {
          filter_enabled = filter_enabled || $(chbs[i]).is(":checked");
        }
        if(!filter_enabled){
            // check mesure
            if((typeof $("#end-mesure").attr('disabled'))==="undefined" || $("#start-mesure").val()!="start"){
                filter_enabled = true;
            }
        }
        if(!filter_enabled){
            // check search input
            if($("#search-input").val().trim()!=""){
                filter_enabled = true;
            }
        }
        if(filter_enabled){
          $("#btn-filter-chapters").removeAttr('disabled');
        }
        else{
          $("#btn-filter-chapters").attr('disabled','disabled');
        }
    }
    
	// Chapter multiselect management
	$('.multiselect').multiselect({
	    buttonText: function(options, select) {
	      return $(select).attr("data-title") + ' (' + options.length + ') <b class="caret"></b>';
	    },
	    onChange: enabledFilter
	});

	// Data 1
	var data1 = [
	    {label: "Performance", value: "performance"},
	    {label: "Discussion", value: "discussion"}
    ];
	$("#mulsel1").multiselect('dataprovider', data1);
  
	// Data 2 : modalités scéniques
	$.ajax({
		url: urlOMS
	})
	.done(function( data ) {
		var o = data.objects;
		var n = data.objects.length;
		var data2 = [];
		for(var i=0;i<n;i++){
			data2.push({label: o[i].name.substr(27), value: o[i].name});
		}
		$("#mulsel2").multiselect('dataprovider', data2);
		$("#mulsel2").multiselect('enable');
	});
  
	// Data 3 : Personnages
	$.ajax({
		url: urlOP
	})
	.done(function( data ) {
		var o = data.objects;
		var n = data.objects.length;
		var data3 = [];
		for(var i=0;i<n;i++){
			data3.push({label: o[i].name.substr(18), value: o[i].name});
		}
		$("#mulsel3").multiselect('dataprovider', data3);
		$("#mulsel3").multiselect('enable');
	});

	// Data 4 : type travail
	$.ajax({
		url: urlOTT
	})
	.done(function( data ) {
		var o = data.objects;
		var n = data.objects.length;
		var data4 = [];
		for(var i=0;i<n;i++){
			data4.push({label: o[i].name.substr(20), value: o[i].name});
		}
		$("#mulsel4").multiselect('dataprovider', data4);
		$("#mulsel4").multiselect('enable');
	});
	
	// on change 
	$(document).on('input', "#search-input", enabledFilter );
	
	// Data 5 : Actes
	$.ajax({
		url: urlOA
	})
	.done(function( data ) {
	    var o = data.objects;
        var n = data.objects.length;
        var data5 = [];
        for(var i=0;i<n;i++){
            data5.push({label: parseInt(o[i].name.substr(12)), value: o[i].name});
        }
        // Sort
        data5.sort(function(a,b){
            return a.label - b.label;
        });
        $("#mulsel5").multiselect('dataprovider', data5);
        $("#mulsel5").multiselect('enable');
	});
    
    // Data 6 : Scènes
    $.ajax({
        url: urlOS
    })
    .done(function( data ) {
        var o = data.objects;
        var n = data.objects.length;
        var data6 = [];
        for(var i=0;i<n;i++){
            data6.push({label: parseInt(o[i].name.substr(13)), value: o[i].name});
        }
        // Sort
        data6.sort(function(a,b){
            return a.label - b.label;
        });
        $("#mulsel6").multiselect('dataprovider', data6);
        $("#mulsel6").multiselect('enable');
    });
    
    // Data 7 : Mesure
    $.ajax({
        url: urlOM
    })
    .done(function( data ) {
        var o = data.objects;
        var n = data.objects.length;
        var data7 = [];
        for(var i=0;i<n;i++){
            data7.push({label: o[i].name.substr(14), value: o[i].name});
        }
        // Sort
        data7.sort(function(a,b){
            var v1 = parseInt(a.label.split(" ")[0]);
            var v2 = parseInt(b.label.split(" ")[0]);
            if(isNaN(v1) || isNaN(v2)){
                return false;
            }
            return v1 - v2;
        });
        // Init select text
        $("#start-mesure").append('<option value="start">Début</option>');
        $.each(data7, function(k,val){
            $("#start-mesure").append('<option value="'+ val.label +'">'+ val.label +'</option>');
            var v = parseInt(val.label);
            if(!isNaN(v)){
                $("#end-mesure").append('<option value="'+ v +'">'+ v +'</option>');
            }
        });
        $("#end-mesure").append('<option value="end" selected="selected">Fin</option>');
    });
    // start-mesure
    $("#start-mesure").on('change', function() {
        var reg = /^\d+$/;
        if(reg.test(this.value)){
            $("#end-mesure").removeAttr('disabled');
        }
        else{
            $("#end-mesure").attr('disabled','disabled');
        }
        enabledFilter();
    });
    
    $(document).on('input', "#search-input", function(){
        if($(this).val()!=""){
            $("#btn-search-annotations").removeAttr('disabled');
        }
        else{
            $("#btn-search-annotations").attr('disabled','disabled');
        }
    });
	
	function buildChapterTable(html){
		$(".chapter-results").removeClass("loader");
		$(".chapter-results").html(html);
		$('.popinfo').popover({ html: true });
		$(".tablesorter").tablesorter({
		    theme : "bootstrap",
		    widthFixed: true,
		    headerTemplate : '{content} {icon}',
		    widgets : [ "uitheme"],
		    widgetOptions : {
		        zebra : ["even", "odd"],
		        filter_reset : ".reset"
		    },
		    headers: { 8: { sorter: false } }
		});
	}
	
	// Search chapters management
	$("#btn-filter-chapters").click(function(e){
		if($("#mulsel1").val()==null && $("#mulsel2").val()==null && $("#mulsel3").val()==null && $("#mulsel4").val()==null && $("#mulsel5").val()==null && $("#mulsel6").val()==null && !((typeof $("#end-mesure").attr('disabled'))==="undefined" || $("#start-mesure").val()!="start") && $("#search-input").val().trim()==""){
			$(".chapter-results").html("<p>Vous devez sélectionner au moins un filtre</p>");
			return false;
		}
		$(".chapter-results").html("<br/><br/>");
		$(".chapter-results").addClass("loader");
		$.ajax({
			url: urlAnnotations,
			data:{
				start_date: $('input[name=start_date]').val(),
				end_date: $('input[name=end_date]').val(),
				annotation_types: ( ($("#mulsel1").val()==null) ? [] : $("#mulsel1").val() ).join(","),
				modalites_sceniques: ( ($("#mulsel2").val()==null) ? [] : $("#mulsel2").val() ).join(","),
				personnages: ( ($("#mulsel3").val()==null) ? [] : $("#mulsel3").val() ).join(","),
				type_travail: ( ($("#mulsel4").val()==null) ? [] : $("#mulsel4").val() ).join(","),
				q: $("#search-input").val(),
				acte: ( ($("#mulsel5").val()==null) ? [] : $("#mulsel5").val() ).join(","),
				scene: ( ($("#mulsel6").val()==null) ? [] : $("#mulsel6").val() ).join(","),
				start_mesure: $("#start-mesure").val(),
				end_mesure: ($("#end-mesure").attr('disabled')) ? "" : $("#end-mesure").val()
			}
		})
		.done(function( html ) {
			buildChapterTable(html);
		})
		.fail(function() {
			$(".chapter-results").removeClass("loader");
			$(".chapter-results").html('<p class="bg-danger">Erreur de chargement</p>');
		});
	});
	

	
	// click-to-remove-tag management for chapter
	$(".chapter-results").on("click", ".chapter-tag-list .glyphicon-remove", function(){
	    if($(this).parent().children().first().hasClass("glyphicon-search")){
            $("#search-input").val("");
        }
        else if($(this).parent().hasClass("type")){
			$("#mulsel1").multiselect('deselect', $(this).parent().text().trim());
		}
		else if($(this).parent().hasClass("modscen")){
			$("#mulsel2").multiselect('deselect', "opera_modalites_sceniques: " + $(this).parent().text().trim());
		}
		else if($(this).parent().hasClass("perso")){
			$("#mulsel3").multiselect('deselect', "opera_personnages: " + $(this).parent().text().trim());
		}
        else if($(this).parent().hasClass("type-travail")){
            $("#mulsel4").multiselect('deselect', "opera_type_travail: " + $(this).parent().text().trim());
        }
        else if($(this).parent().hasClass("acte")){
            $("#mulsel5").multiselect('deselect', "opera_acte: " + $(this).parent().text().split(" ")[1].trim());
        }
        else if($(this).parent().hasClass("scene")){
            $("#mulsel6").multiselect('deselect', "opera_scene: " + $(this).parent().text().split(" ")[1].trim());
        }
        else if($(this).parent().hasClass("mesure")){
            $('#start-mesure')[0].selectedIndex = 0;
            $("#end-mesure").attr('disabled','disabled');
        }
		else if($(this).parent().hasClass("date")){
			$('input[name=start_date]').val("");
			$('input[name=end_date]').val("");
		}
		else if($(this).parent().hasClass("reftext")){
			$('#start-text')[0].selectedIndex = 0;
			$('#end-text')[0].selectedIndex = $('#end-text').children().length - 1;
		}
		$("#btn-filter-chapters").click();
		// manage when nothing is selected
		if($(".chapter-tag-list").children().length==0){
			$(".chapter-results").html('');
		}
	});
	
	// table sorter config
	$.extend($.tablesorter.themes.bootstrap, {
		// these classes are added to the table. To see other table classes available,
		// look here: http://twitter.github.com/bootstrap/base-css.html#tables
		table      : 'table table-bordered',
		caption    : 'caption',
		header     : 'bootstrap-header', // give the header a gradient background
		footerRow  : '',
		footerCells: '',
		icons      : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header
		sortNone   : 'bootstrap-icon-unsorted',
		sortAsc    : 'icon-chevron-up glyphicon glyphicon-chevron-up',     // includes classes for Bootstrap v2 & v3
		sortDesc   : 'icon-chevron-down glyphicon glyphicon-chevron-down', // includes classes for Bootstrap v2 & v3
		active     : '', // applied when column is sorted
		hover      : '', // use custom css here - bootstrap class may not override it
		filterRow  : '', // filter row class
		even       : '', // odd row zebra striping
		odd        : ''  // even row zebra striping
	});
	
	
	// Search annotations management
	$('#searchform').submit(function() {
	    return false;
	});
	
});
