$(document).ready( function () {
	
	$('[data-url]').on('click', function(e) {
    	window.location.href = $(this).data('url');
	});
	
    $( ".datepicker" ).datepicker({
    });
	
	$('select[multiple] > option').mousedown(function(e) {
		if(e.which==1) {
		    e.preventDefault();
		    $(this).prop('selected', !$(this).prop('selected'));
		    return false;
		}
	});
	
	$('.filters-bar').children('select[data-filter]').each(function () {
		var filter_name = $(this).data('filter');
		if(filter_name in loc_qry) {
			$(this).val(loc_qry[filter_name]);
		}
	});
	
	function norm(s) {
		return s.toLowerCase().replace(/[éèê]/g, 'e').replace(/[àâ]/g, 'a').replace(/ç/g, 'c').replace(/ô/g, 'o');
	}
	
	function custom_search2_match(params, data) {
		// https://select2.org/searching#customizing-how-results-are-matched
	    if ($.trim(params.term) === '') {
	      return data;
	    }
	    if (typeof data.text === 'undefined') {
	      return null;
	    }
	    if (norm(data.text).indexOf(norm(params.term)) > -1) {
	      return data;
	    }
	    return null;
	}
	
	$('.filtered-dropdown').select2({
		  theme: 'bootstrap',
		  placeholder: 'Rechercher...',
		  minimumInputLength: 0,
		  matcher: custom_search2_match,
		  language: {
	    	  inputTooShort: function () { return "Veuillez saisir votre recherche..."; },
	    	  errorLoading: function () { return "Erreur de chargement"; },
	    	  searching: function () { return "Recherche en cours…"; },
	    	  noResults: function () { return "Aucun résultat"; },
	    	  loadingMore: function () { return "Chargement de résultats supplémentaires…"; }
	      }
	});
	
	$('#search-bar').select2({
		  theme: 'bootstrap',
		  placeholder: 'Rechercher...',
		  minimumInputLength: 1,
		  ajax: {
		    url: '/search/',
		    dataType: 'json',
		    cache: true,
		    delay: 220
		  },
	      closeOnSelect: false,
	      width : '220px',
	      templateResult: function (state) { return $('<a href="' + state.id + '">' + state.text + '</a>'); },
	      language: {
	    	  inputTooShort: function () { return "Veuillez saisir votre recherche..."; },
	    	  errorLoading: function () { return "Erreur de chargement"; },
	    	  searching: function () { return "Recherche en cours…"; },
	    	  noResults: function () { return "Aucun résultat"; },
	    	  loadingMore: function () { return "Chargement de résultats supplémentaires…"; }
	      }
	});
	
	$('#search-bar').on('change', function() {
		event.preventDefault();
		window.location.href = $(this).first('option').val();
	});
	
	$('#stories').on('change', 'select[data-filter]', function() {
		
		var filters = [];
		var filtersbar = $('#stories > .filters-bar');
		
		filtersbar.children('select').each(function () {
			if (this.value.length > 0) {
				filters.push($(this).data('filter') + "=" + $(this).val());
			}
		});
		
		var url = document.URL;
		var target = url.split('?')[0];
		if (filters.length > 0) {
			target = target + '?' + filters.join('&');
		}
		window.location.href = target;
	});

	$('#stories').on('click', 'a[data-page]', function() {
		
		var filters = [];
		var filtersbar = $('#stories > .filters-bar');
		
		filtersbar.children('select').each(function () {
			if (this.value.length > 0) {
				filters.push($(this).data('filter') + "=" + $(this).val());
			}
		});
		
		var url = document.URL;
		var target = url.split('?')[0];
		if (filters.length > 0) {
			target = target + '?' + filters.join('&') + '&page=' + $(this).data('page');
		} else {
			target = target + '?page=' + $(this).data('page');
		}

		window.location.href = target;
	});
	
	$('#new-story').on('click', function(event) {
		
		event.preventDefault();
		
		var filters = [];
		var filtersbar = $('#stories > .filters-bar');
		
		filtersbar.children('select').each(function () {
			if (this.value.length > 0) {
				filters.push($(this).data('filter') + "=" + $(this).val());
			}
		});
		
		var url = $('#new-story').attr('href');
		var target = url.split('?')[0];
		if (filters.length > 0) {
			target = target + '?' + filters.join('&');
		}
		window.location.href = target;
	});
	
	var epic = getUrlParameter('epic');
	var name = getUrlParameter('name');
	var weight = getUrlParameter('weight');
	var assignee = getUrlParameter('assignee');
	var sprint = getUrlParameter('sprint');
	
	if (epic) { $('#id_epic').val(epic); }
	if (name) { $('#id_name').val(name); }
	if (weight) { $('#id_weight').val(weight); }
	if (assignee) { $('#id_assignees').val([assignee]); }
	if (sprint) { $('#id_sprints').val([sprint]); }
	
	$(document).on('click', function(event) {
	    if(!$(event.target).closest('#user-panel').length) {
	        if($('#user-dropdown').is(":visible")) {
	            $('#user-dropdown').hide();
	        }
	    }
	    if(!$(event.target).closest('#notif-panel').length) {
	    	if($('#notif-dropdown').is(":visible")) {
	    		$('#notif-dropdown').hide();
	    	}
	    }
	    if(!$(event.target).closest('#stories-panel').length) {
	    	if($('#stories-dropdown').is(":visible")) {
	    		$('#stories-dropdown').hide();
	    	}
	    }
	});
	
	$(document).on('click', '#user-show-btn', function(event) {
		event.preventDefault();
		if($('#user-dropdown').is(":visible")) {
			$('#user-dropdown').hide();
		}
		else {
			$('#user-dropdown').show();
		}
	});
	
	$(document).on('click', '#stories-show-btn', function(event) {
		event.preventDefault();
		if($('#stories-dropdown').is(":visible")) {
			$('#stories-dropdown').hide();
		}
		else {
			$('#stories-dropdown').show();
		}
	});
	
	$(document).on('click', '#notif-show-btn', function(event) {
		event.preventDefault();
		if($('#notif-dropdown').is(":visible")) {
			$('#notif-dropdown').hide();
		}
		else {
			$('#notif-dropdown').show();
		}
	});
	
	$(".notif-seen").click(function(event) {
		event.preventDefault();
		var notif = $(this).closest('.notif');
		var notif_id = notif.data('id');
		
        $.ajax({
            type: "POST",
            url: "/notif/seen/" + notif_id + "/",
            data: '{notif_id:' + notif_id + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
            	notif.remove();
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
	});
	
	$(".notif-all-seen").click(function(event) {
		event.preventDefault();
		var notif_list = $('#notif-dropdown').find('.notif-list');
		if (confirm('Êtes vous sûr de vouloir faire disparaitre toutes les notifications ?')) {
			$.ajax({
				type: "POST",
				url: "/notif/allseen/",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (response) {
					notif_list.html('');
					$('.notif-footer').html('<i>Aucune notification à afficher</i>');
					$('.notif-count').html('0');
					$('#notif-dropdown').hide();
				},
				failure: function (response) {
					alert(response.responseText);
				},
				error: function (response) {
					alert(response.responseText);
				}
			});
		}
	});
	
	$('#backlog-editor form input[name=value]').change(function() {
		$(this).closest('form').submit();
	});
	
	$("#backlog-editor").on('submit', 'form', function(event) {
		event.preventDefault();
		
		var action = $(this).attr('action');
		var val_field = $(this).find('input[name=value]');
		
		console.log(action);
		console.log(val_field.val())
		
		$.ajax({
			type: "POST",
			url: action,
			data : { value : val_field.val() },
			success: function (response) {
				val_field.animate({ borderColor: "#009933" }, 1500, function() {
					                val_field.removeAttr('style'); } );
			},
			failure: function (response) {
				val_field.animate({ borderColor: "#ff0000" }, 1500, function() {
	                val_field.removeAttr('style'); } );
				console.log('Ajax failure: ' + response.responseText);
				$("#backlog-editor").unbind('submit');   // Ajax is not working: unbind
				$(this).submit();
			},
			
			error: function (response) {
				val_field.animate({ borderColor: "#ff0000" }, 1500, function() {
	                val_field.removeAttr('style'); } );
				console.log('Ajax error: ' + response.responseText);
				$("#backlog-editor").unbind('submit');   // Ajax is not working: unbind
				$(this).submit();
			}
		});
	
	});
	
	$("#backlog-editor").on('click', '.btn-epic-close', function(event) {
		event.preventDefault();
		
		var action = $(this).attr('href');
		this_btn = $(this);
		
		$.ajax({
			type: "POST",
            url: action,
            success: function (response) {
            	this_btn.addClass('disabled');
            	this_btn.closest('tr').find(".epic-name").addClass('story-closed');
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
		});
	
	});
	
	$("#backlog-editor").on('click', '.btn-epic-reopen', function(event) {
		event.preventDefault();
		
		var action = $(this).attr('href');
		this_btn = $(this);
		name_field = this_btn.closest('tr').find(".epic-name");
		
		$.ajax({
			type: "POST",
			url: action,
			success: function (response) {
				this_btn.addClass('disabled');
				name_field.removeClass('story-closed');
				name_field.html(name_field.html().replace('[Fermée] ', ''));
			},
			failure: function (response) {
				alert(response.responseText);
			},
			error: function (response) {
				alert(response.responseText);
			}
		});
		
	});
	
	$("#sprint-end .story_close").click(function(event) {
		event.preventDefault();
		var story_tr = $(this).closest('tr');
		var story_id = story_tr.data('id');
		
        $.ajax({
            type: "POST",
            url: "/stories/close/" + story_id + "/",
            data: '{story_id:' + story_id + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            success: function (response) {
            	story_tr.find('.btn-cell').html('<a class="button special icon fa-check tool-btn already-checked"></a>');
            	story_tr.find('.btn-cell-2').html('<a class="button special icon fa-mail-forward tool-btn disabled"></a>');
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
	});

	$("#sprint-end .story_reaffect").click(function(event) {
		event.preventDefault();
		var story_tr = $(this).closest('tr');
		var story_id = story_tr.data('id');
		
        $.ajax({
            type: "POST",
            url: "/stories/reaffect/" + story_id + "/",
            success: function (response) {
            	story_tr.find('.btn-cell').html('<a class="button special icon fa-check tool-btn disabled"></a>');
            	story_tr.find('.btn-cell-2').html('<a class="button special icon fa-mail-forward tool-btn already-checked"></a>');
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
	});
	
	$("#sprint-end-table").on('submit', 'form', function(event) {
		event.preventDefault();
		
		var action = $(this).attr('action');
		var val_field = $(this).find('input[name=time_spent]');
		
		console.log(action);
		console.log(val_field.val())
		
		$.ajax({
			type: "POST",
			url: action,
			data : { time_spent : val_field.val() },
			success: function (response) {
				val_field.animate({ borderColor: "#009933" }, 1500, function() {
					                val_field.removeAttr('style'); } );
			},
			failure: function (response) {
				val_field.animate({ borderColor: "#ff0000" }, 1500, function() {
	                val_field.removeAttr('style'); } );
				console.log('Ajax failure: ' + response.responseText);
				$("#sprint-end-table").unbind('submit');   // Ajax is not working: unbind
				$(this).submit();
			},
			
			error: function (response) {
				val_field.animate({ borderColor: "#ff0000" }, 1500, function() {
	                val_field.removeAttr('style'); } );
				console.log('Ajax error: ' + response.responseText);
				$("#sprint-end-table").unbind('submit');   // Ajax is not working: unbind
				$(this).submit();
			}
		});
	
	});

	$("#sprint-end .retro-section input").click(function (event) {
		if (confirm('Le sprint courant va être marqué comme terminé, continuer?')) {
			return true;
		}
	});
	
});