//CHARGEMENT DE LA PAGE
function init_plugin_dynamicform(){
	switch($.urlParam('page')){
		case 'sheet.dynamic.form':
			dynamicform_form_layout();
			dynamicform_field_search();

			window.addEventListener("beforeunload", function (event) {
			  if(window.unsavedModifications) event.returnValue = "Si vous n'enregistrez pas le formulaire, vos dernières modifications seront perdues";
			});
		break;

		default:
		break;
	}
	dynamicform_form_search();

}

function dynamicform_sortableFields(){
	$( ".fields" ).sortable({
      connectWith: ".fields",
      handle: ".btn-field-move"
    }).disableSelection();
}


function dynamicform_form_reset(){
	var layout = $('#form-layout');
	var rowTemplate = $('#layout-row').html();
	layout.find('.row').remove();
	//créeer la ligne/colonne par défaut
	var row = $(rowTemplate);
	layout.append(row);
}

function dynamicform_form_layout(){
	var layout = $('#form-layout');
	var rowTemplate = $('#layout-row').html();

	var defaultType = JSON.parse(atob($('#dynamic-form-form').attr('data-default-type')));

	dynamicform_form_reset();

	//créeer la ligne/colonne par défaut
	if(layout.find('.row').length == 0){
		var row = $(rowTemplate);
		layout.append(row);
	}
	layout.off('click');
	layout.on('click','.btn-row-add',function(){
		var button = $(this);
		var row = button.closest('.row');
		dynamicform_row_add(row);
		window.unsavedModifications = true;
	});
	layout.on('click','.btn-column-add',function(){
		var column = $(this).closest('.column');
		var row = column.closest('.row');
		dynamicform_column_add(row);
		window.unsavedModifications = true;
	});
	layout.on('click','.btn-row-remove',function(){
		var button = $(this);
		if(layout.find('>.row').length < 2) return;
		button.closest('.row').remove();
		window.unsavedModifications = true;
	});
	layout.on('click','.btn-column-remove',function(){
		var button = $(this);
		var row = $(this).closest('.row');

		if(row.find('>.column').length < 2) return;
		button.closest('.column').remove();
		window.unsavedModifications = true;
	});
	layout.on('click','.btn-field-add',function(){
		var button = $(this);
		var column = button.closest('.column');
		var field = dynamicform_field_add(null,column,{type : defaultType,label : 'Nouveau champ'});
		field.find('.btn-field-edit').trigger('click');
	});
	layout.on('click','.btn-field-edit',function(){
		var button = $(this);
		var field = button.closest('.field');
		var data = field.data();

		$.setForm('#dynamic-field-form',data);



		$('#dynamic-field-form').attr('data-id',data.id);

		$('#dynamic-field-form').data('field',field);
		$('.dynamic-field-panel').removeClass('fold');
		$('#dynamic-field-form .label').focus().select();


		var meta = atob_unicode(data.meta);
		if(meta) meta = JSON.parse(meta);
		if(!meta) meta = {};
		$('#deleted-operators input[type="checkbox"]').prop('checked',false);
		if(meta['operator-delete']){
			for(var k in meta['operator-delete']){
				$('#deleted-operators input[type="checkbox"][value="'+meta['operator-delete'][k]+'"]').prop('checked',true);
			}
			init_components('#deleted-operators')
		}


		$('#show-filter').prop('checked',(meta['show-filter'] == true));


		dynamicform_fieldtype_change(data.meta);
	});

	layout.on('click','.btn-field-remove',function(){
		var button = $(this);
		var field = button.closest('.field');
		if(!confirm('Êtes-vous sûr de vouloir supprimer ce champ ?')) return;
		field.remove();
		window.unsavedModifications = true;
	});
}


function dynamicform_row_add(after){
	var clone = $('#form-layout .row:eq(0)').clone();
	clone.find('.column .fields').html('');
	if(after){
		after.after(clone);
	}else{
		$('#form-layout').append(clone);
	}
	dynamicform_sortableFields();
	return clone;
}


function dynamicform_column_add(row){
	var column = $('#form-layout .column:eq(0)');
	var clone = column.clone();
	clone.find('.fields').html('');
	row.append(clone);
	dynamicform_sortableFields();
	return clone;
}


function dynamicform_field_add(field,column,data){
	var fieldTemplate = $('#field-template').html();
	var fieldLine = $(Mustache.render(fieldTemplate,data));
	if(field){
		field.replaceWith(fieldLine);
	}else{
		var fields = column.find('.fields');
		fields.append(fieldLine);
	}

	dynamicform_sortableFields();
	return fieldLine;
}

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


/** FORMULAIRE **/
//Récuperation d'une liste  formulaire dans le tableau #dynamicforms
function dynamicform_form_search(callback){
	$('#dynamic-forms').fill({
		action:'dynamicform_form_search'
	},function(response){
		if(callback!=null) callback();
	});
}

//Ajout ou modification formulaire
function dynamicform_form_save(){
	var data = $('.dynamic-form-form').toJson();
	data.rows = [];

	$('#form-layout > .row').each(function(i){
		var rowLine = this;
		$('> .column',rowLine).each(function(u){
			var columnLine = $(this);
			$('> .fields >li',columnLine).each(function(o){
				var fieldLine = $(this);
				var lineData = fieldLine.data();
				var field = {
					id : lineData.id,
					label : lineData.label,
					type : lineData.type,
					default : lineData.default,
					description : lineData.description,
					mandatory : lineData.mandatory ,
					readonly : lineData.readonly,
					slug : lineData.slug,
					meta : lineData.meta
				}
				if(!data.rows[i]) data.rows[i] = [];
				if(!data.rows[i][u]) data.rows[i][u] = [];
				data.rows[i][u].push(field);
			});
		});
	});

	$.action(data,function(r){
		$('#dynamic-form-form').attr('data-id',r.id);
		$.setForm($('#dynamic-form-form'),r);
		$.urlParam('id',r.id);
		window.unsavedModifications = null;
		dynamicform_field_search();
		$.message('success','Enregistré');
	});
}


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

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


/** CHAMP **/
//Récuperation d'une liste  champ dans le tableau #dynamicfields
function dynamicform_field_search(callback){
	$.action({
		action : 'dynamicform_field_search',
		form : $('#dynamic-form-form').attr('data-id')
	},function(response){
		dynamicform_form_reset();
		var layout = $('#form-layout');
		for (var k in response.rows) {
			var currentRow = dynamicform_row_add();
			for (var i in response.rows[k]) {
				var currentColumn = dynamicform_column_add(currentRow);
				for (var u in response.rows[k][i]) {
					var data = response.rows[k][i][u];
					dynamicform_field_add(null,currentColumn,data);
				}
			}
			currentRow.find('.column:eq(0)').remove();
		}
		if(layout.find('>.row').length>1) layout.find('>.row:eq(0)').remove();
		if(callback!=null) callback();
	});
}


//Ajout ou modification champ
function dynamicform_field_save(){
	var data = $('.dynamic-field-main').toJson();

	var settings = {};
	$('.dynamic-field-settings span').find('>input,select,textarea').each(function(){
		var value = $(this).val();
		if(is_json_string(value))
			value = JSON.parse(value);

		settings[$(this).attr('id')] = value;
	});

	$('.dynamic-field-main #deleted-operators').find('input:checked').each(function(){
		if(!settings['operator-delete']) settings['operator-delete'] = [];
		settings['operator-delete'].push($(this).val());
	});


	if($('#show-filter').prop('checked'))
		settings['show-filter'] = true;



	if(Object.keys(settings).length > 0)
   	data.meta = btoa_unicode(JSON.stringify(settings));

	var field = $('#dynamic-field-form').data('field');

	data.type = JSON.parse(atob($('#type option:selected').attr('data-options')));
	data.id = $('#dynamic-field-form').attr('data-id');

	$('#dynamic-field-form').clear();
	$('#dynamic-field-form').data('field',null);
	dynamicform_field_add(field,null,data);
	$('.dynamic-field-panel').addClass('fold');
	window.unsavedModifications = true;
}

//Mofdification du type de champ
function dynamicform_fieldtype_change(meta){
	$('.dynamic-field-settings').html('');
	$.action({
		action:'dynamicform_field_setting_change',
		type:$('#type').val(),
		settings:meta != null ? meta : ''
	},function(response){
		$('.dynamic-field-settings').append(response);
		init_components($('.dynamic-field-settings'));
	});

}
