$(document).ready(function() {
  jQuery.fn.setupRecipesWidget = function(lang, nbToShow, exceptId) {
    // Ajax-load Recipes in Widget
  	$.ajaxSetup ({  
      cache: false  
    });
  
  	ajax_load_recipes('', exceptId);
	
  	$('.cut-filter').click(function(event){
  		event.preventDefault();
  		var clicked_id = $(this).attr('id').split('cut-id-')[1];
		  
		  $('.cut-filter').removeClass('selected');
		  $(this).addClass('selected');
		  
  		var items = $('#recipes-list-ul');
  		items.fadeOut(200, function(){
  			ajax_load_recipes(clicked_id, exceptId);
  		});
		
  	})

  	function ajax_load_recipes(cutId, exceptId) {
  	  
  		var ajax_load = "<img src='/images/ajax-loader.gif' alt='<?php echo($lang=='en'?'Loading ...':'Chargement ...'); ?>'/>";  

      //  load() functions  
      var loadUrl = "/ajax/recipes-widget-list.php";  
      $("#recipes-list-ul").html(ajax_load).load(loadUrl, { 'lang' : lang, 'cutId' : cutId, 'exceptId' : exceptId}, function() {
  			resetMargin();
  			arrowsDisplay();
  			items.fadeIn(200, function() {
  				
  			});
  		});
  	}

	
  	/* Recipes arrows */
  	var itemWidth = 170 //in px, with of items + margin 
  	var items = $('#recipes-list-ul');
  	var currentItem = 1;

  	$('#next-recipe').live('click', function(event){
  		event.preventDefault();
  		slide(-1);
  	});

  	$('#prev-recipe').live('click', function(event){
  		event.preventDefault();
  		slide(1);
  	});

  	function slide(direction){
  		if( !items.is(':animated') ){
  		  currentItem += direction*-1;
    		arrowsDisplay();
    		
  		  //start from current position
  			currentItemsMarginL = parseInt(items.css('margin-left').split('px')[0]);
  			//animate
  			items.animate({'margin-left' : currentItemsMarginL + (direction * itemWidth)}, 300, "easeOutCubic", function() {

  			});	
  		}

  	}

  	function arrowsDisplay(){
  	  var nbItems = items.children().length;
  	  if(currentItem == 1){
  	    $('#prev-recipe').hide();
  	  } else {
  	    $('#prev-recipe').show();
  	  }

  	  if(currentItem >= nbItems - (nbToShow - 1)){
  	    $('#next-recipe').hide();
  	  } else {
  	    $('#next-recipe').show();
  	  }
  	}
  	
  	function resetMargin(){
      var items = $('#recipes-list-ul');
      currentItemsMarginL = 0;
      currentItem = 1;
      items.css({'margin-left':'0'});
  	}
  }
});
  
