//CHARGEMENT DE LA PAGE
function init_plugin_workflow(){
	switch($.urlParam('page')){
		case 'sheet.workflow':
			workflow_workflow_type_change();
			workflow_effect_search();
			workflow_lock_input();
		break;
	}

	//Tri possible des effets de workflow
	$('#workflow-effects tbody').sortable({
		handle :'.fa-arrows-alt',
		axis :'y',
		update : function( event, ui ){
			var data = $('#workflow-effect-form').toJson();
			data.action = 'workflow_workflow_effect_sort';
			data.workflow = $('#workflow-form').attr('data-id');
			data.sort = [];
			$('#workflow-effects tbody tr:visible').each(function(){
				var tr = $(this);
				data.sort.push(tr.attr('data-id'));
			});

			$.action(data);
		}
	});
	$('#workflows').sortable_table({
		onSort : workflow_workflow_search
	});
}

//verouillez les champs en fonction du type de workflow (liste, entité ou général)
function workflow_lock_input(){
	if( $('#workflow-form').attr('data-id') != ''){
		$('.create-only').attr('disabled','disabled');
	}else{
		$('.create-only').removeAttr('disabled','disabled');
	}
}


/** WORKFLOW **/

//Récuperation d'une liste de workflow dans le tableau #workflows
function workflow_workflow_search(callback){
	var box = new FilterBox('#filters');
	$('#workflows').fill({
		action:'workflow_workflow_search',
		filters: box.filters(),
		sort: $('#workflows').sortable_table('get')
	},function(response){
		$('.results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément workflow
function workflow_workflow_save(){
	var data = $('#workflow-form').toJson();

	if($('#workflow-effects [data-slug="entity"].open').length!=0){
		$.message('warning','Un effet est encore en cours d\'edition, merci de le valider avant d\'enregistrer le workflow entier');
		return;
	}

	data.cause =  new FilterBox('#cause-filters').filters().advanced;
	data.effect =  new FilterBox('#effect-filters').filters().advanced;
	$.action(data,function(r){
		$.urlParam('id',r.id);
		$('#workflow-form').attr('data-id',r.id);
		workflow_lock_input();
		workflow_cause_search();
		workflow_effect_search();
		workflow_event_search();
		$.message('success','Enregistré');
	});
}


//Suppression d'élement workflow
function workflow_workflow_delete(element,event){
	event.stopPropagation();
	event.preventDefault();
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('li');

	$.action({
		action: 'workflow_workflow_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}

//Lancement manuel d'un workflow
function workflow_workflow_run(element){
	$('.btn-workflow-execute').addClass('btn-preloader');
	$.action({
		action : 'workflow_workflow_run',
		id : $('#workflow-form').attr('data-id'),
		eventSlug : $(element).closest('li').attr('data-slug')
	},function(r){
		$.message('success','Executé');
	});
}

//Modification du type d'un workflow (verouillage de certains champs et récuperations des causes/effets/evenement lié a ce type)
function workflow_workflow_type_change(){

	if($('#type').val() == 'global'){
		$('.entity-group').addClass('hidden');
	}else{
		$('.entity-group').removeClass('hidden');
	}

	workflow_cause_search();
	workflow_event_search();
}


/** WORKFLOWEVENT **/
//Récuperation d'une liste de workflowevent dans le tableau #workflowevents
function workflow_event_search(callback){
	var box = new FilterBox('#filters');
	$('#workflow-events').fill({
		action:'workflow_event_search',
		workflow : $('#workflow-form').attr('data-id'),
		filters: box.filters(),
		type: $('#type').val(),
		entity: $('#entity').val(),
		sort: $('#workflow-events').sortable_table('get')
	},function(response){
		$('#event').html('<option value="">-</option>');
		for(var slug in response.events){
			$('#event').append('<option value="'+slug+'">'+response.events[slug]+'</option>');
		}
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément workflowevent
function workflow_workflow_event_save(){
	var data = $('#workflow-event-form').toJson();
	data.workflow = $('#workflow-form').attr('data-id');
	$.action(data,function(r){

			$('#workflow-event-form').attr('data-id','');
			workflow_event_search();

		$.message('success','Enregistré');
	});
}

//Suppression d'élement workflowevent
function workflow_workflow_event_delete(element){
	var line = $(element).closest('li');
	$.action({
		action: 'workflow_workflow_event_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}


/* WORKFLOW CAUSES */
//Récuperation d'une liste de workfloweffect dans le tableau #workfloweffects
function workflow_cause_search(callback){
	$.action({
		action:'workflow_cause_search',
		workflow: $('#workflow-form').attr('data-id'),
		type: $('#type').val(),
		entity: $('#entity').val(),
		sort: $('#workflow-effects').sortable_table('get')
	},function(response){
		$('#cause-filters').remove();
		$('.workflow-causes .advanced-search-box').remove();
		$('.workflow-cause-filters').html('');
		for (var i  in response.filters) {
			$('.workflow-cause-filters').append(response.filters[i]);
		}
		var filters = '';
		for(var k in response.causes.available){
			filters+='<option value="'+response.causes.available[k].slug+'" '+response.causes.available[k].attributes+'>'+response.causes.available[k].label+'</option>'
		}

		var causes =  $('#cause-filters-template').template({enabled : response.causes.enabled,filters : filters});
		causes.removeClass('hidden');
		causes.attr('id','cause-filters').attr('data-type','filter');
		$('#cause-filters-template').after(causes);

		init_components();
		if(callback!=null) callback();
	});
}


/** WORKFLOWEFFECT **/
//Récuperation d'une liste de workfloweffect dans le tableau #workfloweffects
function workflow_effect_search(callback){
	$('#workflow-effects').fill({
		action:'workflow_effect_search',
		workflow: $('#workflow-form').attr('data-id'),
		type: $('#type').val(),
		entity: $('#entity').val(),
		sort: $('#workflow-effects').sortable_table('get')
	},function(response){
		$('#workflow-effects tbody tr:visible').each(function(){
			var slug = $(this).attr('data-slug');
			if(window['workflow_effect_'+slug+'_init']) window['workflow_effect_'+slug+'_init']($(this));
		});
		init_components('#workflow-effects');
		if(callback!=null) callback();
	});
}


//Ajout ou modification d'élément workfloweffect
function workflow_workflow_effect_save(){
	var data = $('#workflow-effect-form').toJson();

	data.workflow = $('#workflow-form').attr('data-id');
	$.action(data,function(r){
			$('#workflow-effect-form').attr('data-id','');
			workflow_effect_search(function(){
				workflow_workflow_effect_edit($('#workflow-effects [data-id="'+r.id+'"] .btn-edit'));
			});
		$.message('success','Enregistré');
	});
}


//Récuperation ou edition d'élément workfloweffect
function workflow_workflow_effect_edit(element){
	//var line = $(element).closest('tr');
	var button = $(element);
	var tr = button.closest('tr');
	var form = tr.find('.workflow-effect-form');


	if(!tr.hasClass('open')){
		$('#workflow-effects tr').removeClass('open');
		//open
		tr.addClass('open');
		form.find('input:eq(0)').focus();
	}else{

		//save & close

		data = {};
		data.id = tr.attr('data-id');
		data.action = 'workflow_workflow_effect_save';
		data.values = {};

		$('.workflow-effect-form [data-id]',tr).each(function(){
			var input = $(this) ;
			var id = input.attr('data-id');
			if(!id) return;
			if(input.attr("type")=='checkbox' || input.attr("type")=='radio'){
				data.values[id] = (input.is(':checked')?1:0);
			} else if(input.attr("type")=='file'){
				if(!input[0].files.length) return;
				if(input[0].files.length == 1){
					data.values[id] = input[0].files[0];
				} else {
					data.values[id] = {};
					for(var i=0; i<input[0].files.length; ++i)
						data.values[id][i] = input[0].files[i];
				}
			} else {
				data.values[id] = input.val();
			}
		});

		$('.workflow-effect-form [data-type="filter"]',tr).each(function(){
			var box = new FilterBox(this);
			data.values[$(this).attr('data-id')] = box.filters();
		});

		$.action(data,function(r){
			tr.removeClass('open');
			$.message('success','Enregistré');
		});


	}
}

//Suppression d'élement workfloweffect
function workflow_workflow_effect_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('tr');

	$.action({
		action: 'workflow_workflow_effect_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}

//Enregistrement des configurations
function workflow_setting_save(){
	$.action({
		action: 'workflow_setting_save',
		fields:  $('#workflow-setting-form').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}
