vanilla.namespace('joblib.offre.diaporama');

joblib.offre.diaporama =
{
    marginWidth : 30,
    index : -1,
    offres : null,

    init : function(properties)
    {
	this.view	= $("#view-" + properties.viewId);
	this.offres	= this.view.find("li.offre");
	this.content	= this.offres.parent();

	/*
	   on ajoute un div avant et après
	*/

	this.content.append($(document.createElement("li")).addClass("margin").css({"float":"left", width:this.marginWidth, height:1}));
	this.content.prepend($(document.createElement("li")).addClass("margin").css({"float":"left", width:this.marginWidth, height:1}));

	/*
	   On calcul la width du container
	*/

	this.content.width(this.offres.outerWidth()*this.offres.length + this.marginWidth*2);

	/*
	   Initialisation du slider
	*/

	$("a.next", this.view).click
	(
	    function()
	    {
		this.nextOffre();
	    }
	    .bind(this)
	);

	$("a.previous", this.view).click
	(
	    function()
	    {
		this.previousOffre();
	    }
	    .bind(this)
	);

	this.gotoOffreByIndex(0, true);
    },

    nextOffre : function()
    {
	if ( !this.gotoOffreByIndex(this.index+1) )
	{
	    this.gotoOffreByIndex(0);
	    this.boundaryEffect(-1, true);
	}
    },

    previousOffre : function()
    {
	if ( !this.gotoOffreByIndex(this.index-1) )
	{
	    this.boundaryEffect(-1);
	}
    },

    gotoOffre : function(offre, doNotAnimate)
    {
	offre = $(offre).get(0);
	var index = 0;
	this.offres.each
	(
	    function(i)
	    {
		if ( this == offre )
		{
		    index = i;
		    return false;
		}

		return true;
	    }
	);

	this.gotoOffreByIndex(index, doNotAnimate);
    },

    gotoOffreByIndex : function(i, doNotAnimate)
    {
	if ( i >= 0 && i < this.offres.length )
	{
	    var x = this._getOffreOffset(i);
	    if ( doNotAnimate )
	    {
		this.content.parent().stop(true).scrollLeft(x);
	    }
	    else
	    {
		if ( Math.abs(this.index - i) > 1 )
		{
		    this.content.parent().stop(true).animate({scrollLeft:x}, {duration:800,easing:"easeInBack"});
		}
		else
		{
		    this.content.parent().stop(true).animate({scrollLeft:x}, {duration:800,easing:"easeInOutBack"});
		}
	    }

	    this.index = i;
	    return true;
	}

	return false;
    },

    _getOffreOffset : function(i)
    {
	return i*this.offres.eq(0).outerWidth() + this.marginWidth;
    },

    boundaryEffect : function(coef, doNotStop)
    {
	// on montre qu'on est à la fin
	var left = this._getOffreOffset(this.index);
	var p = this.content.parent();
	
	if ( !doNotStop )
	{
	    p.stop(true, true);
	}

	p.animate({"scrollLeft": left + coef*20}, {duration : 100}).animate({"scrollLeft": left}, {duration : "fast"});
    }
};

