$(document).ready(function(){
	function updateSelection(i) {
		var line = /^(\d+).+$/.exec($('.nb_articles:first').html()),
			count = line ? parseInt(line[1], 10) + i : i,
			msg = "";
		if ( count == 1 ) {
			msg = "1 article";
		} else if ( count > 1 ) {
			msg = count+" articles";
		} else {
			msg = "Pas d'article";
		}
		$('.nb_articles').html(msg);
		// case à cocher sur contact
		if ( count == 0 && ($label = $('#label-send-selection')) && $label.length ) {
			$label.fadeOut();
		}
	}
	// selection
	$('.btn_selection_add, .btn_selection_remove').live('click', function(){
		var action = $(this).hasClass('btn_selection_add') ? 'add' : 'remove',
			id = parseInt(this.href.replace(/^.+#([0-9]+)$/, '$1'), 10),
			colonne_selection = $(this).parents('.col-smenu').length,
			that = this;
		$.ajax({
			type: 'get',
			dataType: 'json',
			url: App.settings.basePath+'api.php',
			data: 'method=selection&format=json&action='+action+'&id='+id,
			success: function(data){
				// appellé depuis la colonne selection
				if ( colonne_selection ) {
					$(that).parent('.tpl-catalogue').fadeOut(function(){
						$(this).remove();
						if ( !$('.col-smenu .tpl-catalogue').length ) {
							$('.col-smenu .titre-page').html('Votre sélection est vide');
						}
						updateSelection(-1);
					})
					return;
				}
				// appellé depuis la page produit
				var msg_class = data.status == 1 ? 'valid' : 'alert',
					prefix = data.status == 1 ? '&#x2713;' : '&#10007;';
				// boutons
				var btns = {
					'remove' : '<a href="#'+id+'" class="produit-lien btn_selection_remove"><b>&times;</b> Retirer de ma sélection</a>',
					'add' : '<a href="#'+id+'" class="produit-lien btn_selection_add"><b>+</b> Ajouter à ma sélection</a>'
				};
				$(that).fadeOut(500, function(){
					$msg = $('<div class="msg_'+msg_class+'" style="display:none;">'+prefix+' '+data.msg+'</div>');
					$(that).after($msg);
					$msg.fadeIn().delay(1500).fadeOut(function(){
						// pas d'erreur, on affiche le bouton inverse
						if ( data.status == 1 ) {
							var btn = btns[ action == 'add' ? 'remove' : 'add' ];
						// sinon on affiche le bouton initial
						} else {
							var btn = btns[action];
						}
						$(that).after(btn).fadeIn();
						$(that).remove();
					});
				});
				if ( data.status == 1 ) {
					updateSelection(action == 'add' ? 1 : -1);
				}
			},
			error: function(){
			//	$('#localisation-status').html("Error loading data");
			}
		});
		return false;
	});
});
