$(document).ready(function () {
	
	// Chapter multiselect management
	$('.chapters .multiselect').multiselect({
	    buttonText: function(options, select) {
	      return $(select).attr("data-title") + ' (' + options.length + ') <b class="caret"></b>';
	    },
	    onChange: function(element, checked) {
	      var filter_enabled = false;
	      var chbs = $(".chapters input:checkbox");
	      for (var i = chbs.length - 1; i >= 0; i--) {
	        filter_enabled = filter_enabled || $(chbs[i]).is(":checked");
	      };
	      if(filter_enabled){
	        $("#btn-filter-chapters").removeAttr('disabled');
	      }
	      else{
	        $("#btn-filter-chapters").attr('disabled','disabled');
	      }
	    }
	});
	// Annotations multiselect management
	$('.annotations .multiselect').multiselect({
	    buttonText: function(options, select) {
	      return $(select).attr("data-title") + ' (' + options.length + ') <b class="caret"></b>';
	    },
	    buttonContainer: '<div class="btn-group width100percent" />',
	    buttonClass: 'btn btn-default width100percent disabled'
	});

	// Data 1
	var data1 = [
	    {label: "Performance", value: "performance"},
	    {label: "Discussion", value: "discussion"}
    ];
	$("#mulsel1").multiselect('dataprovider', data1);
  
	// Data 2 : modalités scéniques
	$.ajax({
		url: urlMS
	})
	.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(21), value: o[i].name})
		}
		$("#mulsel2").multiselect('dataprovider', data2);
		$("#mulsel2").multiselect('enable');
	});
  
	// Data 3 : Personnages
	$.ajax({
		url: urlP
	})
	.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(12), value: o[i].name})
		}
		$("#mulsel3").multiselect('dataprovider', data3);
		$("#mulsel3").multiselect('enable');
	});

	// Data 4 : type interventions
	$.ajax({
		url: urlTI
	})
	.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(12), value: o[i].name.substr(12)})
		}
		$("#mulsel4").multiselect('dataprovider', data4);
		$("#mulsel4").multiselect('enable');
	});
	$(document).on('input', "#search-input", function(){
		if($(this).val()!=""){
			$("#btn-search-annotations").removeAttr('disabled');
		}
		else{
			$("#btn-search-annotations").attr('disabled','disabled');
		}
	});
	
	// Data 5 : ref text
	$.ajax({
		url: urlRT
	})
	.done(function( data ) {
		var o = data.objects;
		var n = data.objects.length;
		var data5 = [];
		var re = /^\d+-\d+$/;
		for(var i=0;i<n;i++){
			var l = o[i].name;
			if(l.substr(0, 10)=="ref_text: "){
				var rt = l.substr(10);
				if(re.test(rt)){
					var a = rt.split("-");
					data5.push({one: parseInt(a[0]), two: parseInt(a[1]) });
				}
			}
		}
		// Sort
		data5.sort(function(a,b){
			if((a.one - b.one)!=0){
				return a.one - b.one;
			}
			return a.two - b.two;
		});
		// Init select text
		$("#start-text").append('<option value="start">Début</option>');
		$.each(data5, function(k,val){
			var v = val["one"] + "-" + val["two"];
			$("#start-text").append('<option value="'+ v +'">'+ v +'</option>');
			$("#end-text").append('<option value="'+ v +'">'+ v +'</option>');
		});
		$("#end-text").append('<option value="end" selected="selected">Fin</option>');
		$(".theatre-text select").on("change", function(){
			$("#btn-filter-chapters").removeAttr('disabled');
			document.getElementsByTagName("iframe")[0].contentWindow.location.hash = $(this).val();
		});
	});
	
	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: { 3: { sorter: false } }
		});
	}
	
	// Search chapters management
	$("#btn-filter-chapters").click(function(e){
		if($("#mulsel1").val()==null && $("#mulsel2").val()==null && $("#mulsel3").val()==null){
			$(".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: urlChapters,
			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(","),
				start_text: $("#start-text").val(),
				end_text: $("#end-text").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().hasClass("type")){
			$("#mulsel1").multiselect('deselect', $(this).parent().text().trim());
		}
		else if($(this).parent().hasClass("modscen")){
			$("#mulsel2").multiselect('deselect', "modalites_sceniques: " + $(this).parent().text().trim());
		}
		else if($(this).parent().hasClass("perso")){
			$("#mulsel3").multiselect('deselect', "personnages: " + $(this).parent().text().trim());
		}
		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
	
	function searchAnnotations(){
		$(".annotation-results").html("<br/><br/>");
		$(".annotation-results").addClass("loader");
		$.ajax({
			url: urlAnnotations,
			data:{
				q: $('#search-input').val(),
				type_inter: ( ($("#mulsel4").val()==null) ? [] : $("#mulsel4").val() ).join(",")
			}
		})
		.done(function(html){
			$(".annotation-results").removeClass("loader");
			$(".annotation-results").html(html);
			if($('#search-input').val() && $('#search-input').val()!=""){
				$("#btn-filter-annotations").click();
			}
		})
		.fail(function() {
			$(".annotation-results").removeClass("loader");
			$(".annotation-results").html('<p class="bg-danger">Erreur de chargement</p>');
		});
	}
	
	$("#btn-search-annotations").click(function(e){
		e.preventDefault();
		if($("#search-input").val()==""){
			$(".annotation-results").html("<p>Vous devez indiquer un terme pour la recherche.</p>");
			return false;
		}
		searchAnnotations();
	});
	
	$("#btn-filter-annotations").click(function(e){
		if($("#mulsel4").val() && $("#mulsel4").val()!=""){
			var filters = $("#mulsel4").val();
			var nb_filters = filters.length;
			if($('#search-input').val()!=""){
				$( ".searched-annot" ).each(function(index){
					var type_inter = $(this).attr("data-type-inter").split(", ");
					var found = true;
					for(var i=0;i<nb_filters;i++){
						if(type_inter.indexOf(filters[i])==-1){
							found = found && false;
						}
					}
					found ? $(this).show() : $(this).hide();
				});
			}
			else{
				searchAnnotations();
			}
		}
		else{
			$( ".searched-annot" ).each(function(j){
				$(this).show();
			});
		}
		// We display the clickable/removable tags.
		// First we remove all childs but the searched-term one
		if($(".annot-tag-list").children().first().children().first().hasClass("glyphicon-search")){
			$(".annot-tag-list").find("li:gt(0)").remove();
		}
		else{
			$(".annot-tag-list").children().remove();
		}
		if($("#mulsel4").val() && $("#mulsel4").val()!=""){
			var filters = $("#mulsel4").val();
			var nb_filters = filters.length;
			for(var i=0;i<nb_filters;i++){
				if(filters[i].trim()!=""){
					$(".annot-tag-list").append('<li class="small searched-tag">' + filters[i] + ' <span class="glyphicon glyphicon-remove small"></span></li>');
				}
			}
		}
		// Update number displayed
		$(".nb-annotations-found").html($('.annotation-results > div.searched-annot:visible').length);
	});
	
	// click-to-remove-tag management for annotations
	$(".annotation-results").on("click", ".annot-tag-list .glyphicon-remove", function(){
		if($(this).parent().children().first().hasClass("glyphicon-search")){
			$("#search-input").val("");
		}
		else{
			$("#mulsel4").multiselect('deselect', $(this).parent().text().trim());
		}
		$("#btn-filter-annotations").click();
		// manage when nothing is selected
		if($(".annot-tag-list").children().length==0 && $(".annotation-results .info").length==0){
			$(".annotation-results").html('');
		}
	});
	
	// Annotations to chapters management
	$(".annotation-results").on("click", ".annot-to-chapter", function(){
		// First we unselect chapter filters
	    $('option', $('#mulsel1')).each(function(element) { $(this).removeAttr('selected').prop('selected', false); });
	    $('#mulsel1').multiselect('refresh');
	    $('option', $('#mulsel2')).each(function(element) { $(this).removeAttr('selected').prop('selected', false); });
	    $('#mulsel2').multiselect('refresh');
	    $('option', $('#mulsel3')).each(function(element) { $(this).removeAttr('selected').prop('selected', false); });
	    $('#mulsel3').multiselect('refresh');
	    // Then we request
		$(".chapter-results").html("<br/><br/>");
		$(".chapter-results").addClass("loader");
		var bla = [];
		$('.annotation-results > div.searched-annot:visible').each(function(index){
			bla.push({data: $(this).attr("data-start"), iri_id: $(this).attr("data-content") }); 
		});
		if(bla.length==0){
			$(".chapter-results").removeClass("loader");
			return;
		}
		$.post(
			urlChapters,
			{
				annotations: JSON.stringify(bla), 
				csrfmiddlewaretoken: csrf_token
			}, 
			function( html ) {
				buildChapterTable(html);
			}
		)
		.fail(function() {
			$(".chapter-results").removeClass("loader");
			$(".chapter-results").html('<p class="bg-danger">Erreur de chargement</p>');
		});
	});
	
	// Chapter to annotations management
	$(".chapter-results").on("click", ".chapter-to-annot", function(){
		// First we unselect chapter filters
	    $('option', $('#mulsel4')).each(function(element) { $(this).removeAttr('selected').prop('selected', false); });
	    $('#mulsel4').multiselect('refresh');
	    // Then we request
		$(".annot-results").html("<br/><br/>");
		$(".annot-results").addClass("loader");
		var bla = [];
		$('.chapter-data').each(function(index){
			bla.push({start: $(this).attr("data-start"), end: $(this).attr("data-end"), iri_id: $(this).attr("data-content") }); 
		});
		if(bla.length==0){
			$(".annotation-results").removeClass("loader");
			return;
		}
		$.post(
			urlAnnotations,
			{
				chapters: JSON.stringify(bla), 
				csrfmiddlewaretoken: csrf_token
			}, 
			function( html ) {
				$("#search-input").val("   "); // trick to simply enable filter annotations
				$(".annotation-results").removeClass("loader");
				$(".annotation-results").html(html);
			}
		)
		.fail(function() {
			$(".annotation-results").removeClass("loader");
			$(".annotation-results").html('<p class="bg-danger">Erreur de chargement</p>');
		});
	});
	
	// Filter chapter to annotations
	$(".chapter-results").on("click", ".filter-chapter-annot", function(){
		var $tr = $(this).parent().parent();
		// green line or not
		($(this).prop('checked')==true) ? $tr.addClass("success") : $tr.removeClass("success");
		filterAnnotationsWithChapters();
	});
	
	function filterAnnotationsWithChapters(){
		// Remove all childs but the searched-term one
		if($(".annot-tag-list").children().first().children().first().hasClass("glyphicon-search")){
			$(".annot-tag-list").find("li:gt(0)").remove();
		}
		else{
			$(".annot-tag-list").children().remove();
		}
		// We build the the array of content ids and timecodes
		var id_tc = {};
		$(".chapter-results input[type=checkbox]:checked").each(function(index){
			var $tr = $(this).parent().parent();
			var iri_id = $tr.attr("data-content");
			if(!(iri_id in id_tc)){
				id_tc[iri_id] = [];
			}
			id_tc[iri_id].push({ start: parseInt($tr.attr("data-start")), end: parseInt($tr.attr("data-end")) }); 
		});
		$('.annotation-results > div.searched-annot').each(function(index){
			// annot in timecode and content ?
			var show = true;
			var iri_id = $(this).attr("data-content");
			if(iri_id in id_tc){
				show = true;
			}
			else{
				show = false;
			}
			show ? $(this).show() : $(this).hide();
		});
		
		if($(".chapter-results input[type=checkbox]:checked").length==0){
			$('.annotation-results > div.searched-annot').show();
		}
		// Update number displayed
		$(".nb-annotations-found").html($('.annotation-results > div.searched-annot:visible').length);
	}
	
	// spectacle theatre text management
	$(".toggle-text").click(function(e){
		if($(".theatre-text:visible").length==0){
			$(".theatre-text").show();
			$(".toggle-text .glyphicon-play").addClass("rotate-90");
		}
		else{
			$(".theatre-text").hide();
			$(".toggle-text .glyphicon-play").removeClass("rotate-90");
		}
	});
});
