/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var _factorX;
var _postX;
var _arr;
var _newX ;
var _relacion
var _desplazar

$(document).ready(function()
{
    //('.previous_button').removeClass("next_button");
    $('.previous_button').addClass("disable");

    $('.next_button').bind('click',  function(e)
    {
        var _boton = $(this)
        _boton.parent().find('.previous_button').removeClass("disable");

        getPos($(this), 'next');
        
        if((_desplazar - (-1* _postX)) < (4 * _factorX))
        {
            _newX = _postX - (_desplazar - (-1* _postX));
        }

        if( (_desplazar - (-1 * _postX)) != 0  &&  _arr.length > 4)
        {
            $(this).parent().find('.allItems').fadeTo("normal", 0.33);			
            $(this).parent().find('.allItems').animate({
                "left":(_newX + "px")
            }, 1000);
            
            $(this).parent().find('.allItems').fadeTo("normal", 1, function ()
            {
                getPos($(this), 'next');
                if( (_desplazar - (-1 * _postX) ) == 0)
                {
                    _boton.parent().find('.next_button').addClass("disable");
                }
            });            
        }
    });

    $('.previous_button').bind('click',  function(e)
    {    
         var _boton = $(this)
        _boton.parent().find('.next_button').removeClass("disable");

        getPos($(this),'prev');

        if(_postX + (4 * _factorX) >=  0)
        {
            _newX = 0;
        }

        if(_postX != 0 && _arr.length > 4)
        {
            $(this).parent().find('.allItems').fadeTo("normal", 0.33);
            $(this).parent().find('.allItems').animate({
                "left":(_newX + "px")
            }, 1000);

            $(this).parent().find('.allItems').fadeTo("normal", 1, function ()
            {
                _postX = parseFloat($(this).parent().find('.allItems').css('left'))
                if(_postX == 0)
                {                    
                    _boton.parent().find('.previous_button').addClass("disable");
                }
            });
        }

    });

});


function getPos(button, dir)
{
    _factorX = parseFloat($('.carouselList').css('width')) + parseFloat($('.carouselList').css('margin-right')) + 14;

    if(isNaN(parseFloat(button.parent().find('.allItems').css('left'))))
    {
        _postX = 0;
    }
    else
    {
        _postX = parseFloat(button.parent().find('.allItems').css('left'))
    }

    _arr = jQuery.makeArray( button.parent().find('.carouselList'));
    _newX = (dir== 'next') ? _postX - (4 * _factorX) : _postX + (4 * _factorX);

    _relacion = (_arr.length * _factorX) / (4 * _factorX);
    _desplazar = (_relacion - 1) * (4 * _factorX);

}
