//CHARGEMENT DE LA PAGE
function init_plugin_contact(){
	switch($.urlParam('page')){
		case 'sheet.contact.person':
			contact_contact_search();
		break;
		default:
		break;
	}
	$('#contact-persons').sortable_table({
		onSort : contact_contact_person_search
	});
}

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




/** CONTACT **/
//Récuperation d'une liste  contact dans le tableau #contactpersons
function contact_contact_person_search(callback,exportMode){
	var box = new FilterBox('#filters');
	$('#contact-persons').fill({
		action:'contact_contact_person_search',
		filters: box.filters(),
		sort: $('#contact-persons').sortable_table('get'),
		export:  !exportMode ? false : exportMode
	},function(response){
		$('.results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}

//Ajout ou modification contact
function contact_contact_person_save(){
	var data = $('#contact-person-form').toJson();
	$.action(data,function(r){
		$('#contact-person-form').attr('data-id',r.id);
		$.urlParam('id',r.id);
		$.message('success','Enregistré');
	});
}


//Suppression contact
function contact_contact_person_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('.item-line');
	$.action({
		action: 'contact_contact_person_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Contact supprimé');
	});
}

/* CONTACT info*/

function contact_contact_add(element,data){
	if(element){
		var line = $(element).closest('li');
	}else{
		var line = $('#contact-list li:eq(0)');
	}

	var newline = line.clone().clear();
	line.after(newline);

	if($('#contact-list li:eq(0) .value').val()=='') $('#contact-list li:eq(0)').remove();

	if(data){
		newline.find('.type').val(data.type);
		newline.find('.value').val(data.value);
	}

	contact_contact_save();
}

function contact_contact_remove(element){
	var line = $(element).closest('li');
	if($('#contact-list li').length==1){
		line.clear();
	}else{
		line.remove();
	}

	contact_contact_save();
}
function contact_contact_search(){
	var contacts = JSON.parse(atob($('#contacts').val()));
	for(var k in contacts){
		contact_contact_add(null,contacts[k]);
	}
}
function contact_contact_save(){
	var contacts = [];
	$('#contact-list li').each(function(){
		var line = $(this);
		contacts.push({
			type : line.find('.type').val(),
			value : line.find('.value').val()
		});
	});
	$('#contacts').val(btoa(JSON.stringify(contacts)));
}