
var Carrusel = new Class({

    options: {
        images : '#carrusel_content a',
        container : '#carrusel_wrapper ul',

        LeftButton : '#scrollLeft',
        RightButton : '#scrollRight',

        LoadImagesWith : '',
        imageID : "lightboxed" ,


        zoom: {
            normal: {
                height: 82,
                width: 109,
                paddingTop: 2 + 'px',
                paddingBottom: 2 + 'px',
                paddingLeft: 3 + 'px',
                marginRight: 2 + 'px'
            },
            onmouse: {
                height: 86,
                width: 114,
                paddingTop: 0 + 'px',
                paddingBottom: 0  + 'px',
                paddingLeft: 0 + 'px',
                marginRight: 0 + 'px'
             },
            general: {
                    'height': 82,
                    'width': 0,
                    'border': 'none',
                    'padding-top': 2 + 'px',
                    'padding-bottom': 2 + 'px',
                    'padding-left': 3 + 'px',
                    'margin-right': 2 + 'px',
                    'display': 'inline'
            },
            delay: 500 ,
            fx: Fx.Transitions.Sine.easeInOut
        },

        ViewRange : 6 ,
        StartIndex : 0,
        Step: 1
    },



    initialize: function(options){
        //Inicializacion de las variables internas
        for (var i in options)
            this.options[i]=options[i];
        this.enlaces = $$(this.options.images) ;
        this.container = $E(this.options.container);

        //Numero total de imagenes
        this.ImagesNum = this.enlaces.length ;
        if (this.ImagesNum < this.options.ViewRange){
            this.options.ViewRange=this.ImagesNum;
        }
        this.imagesloaded = [] ;

        var zoom = this.options.zoom;
        for(var i=0; i<this.ImagesNum; i++){
            var img = this.enlaces[i].getElement('img');
            if (img){
                 img.setStyles(zoom.normal);
                 img.setAttribute('alt', this.enlaces[i].getAttribute("alt"));
                 img.setAttribute('title', this.enlaces[i].getAttribute('fullname'));
                 //img.setAttribute('src', this.enlaces[i].getAttribute('href') + this.options.LoadImagesWith);
                 img.addEvent('mouseover', function() {
    	                this.setStyles(zoom.onmouse)
                 });
                 img.addEvent('mouseleave', function() {
                     this.setStyles(zoom.normal)
                 });
                 this.imagesloaded[i] = true;
            }
            else{
                this.imagesloaded[i] = false;
            }
        }
        this.createEvents();
        if (this.options.StartIndex > this.ImagesNum){
            this.options.StartIndex = 0;
        }
        this.viewrangeNow = this.calculateRange(this.options.StartIndex );
        //this.moveContainer(1);
        if( this.viewrangeNow.start >= 0  &&  this.viewrangeNow.end < this.ImagesNum) {
            this.loadImageRange(this.viewrangeNow.start , this.viewrangeNow.end, 0);
        }
    },

    pageBack: function(){
        //Se asociaria al evento de retroceder pagina
        var newRange = this.calculateRange(this.viewrangeNow.start - this.options.Step);
        this.loadImageRange(newRange.start , newRange.end, -1);
        if (newRange.start != this.viewrangeNow.start){
            this.viewrangeNow = newRange;
            //this.moveContainer(-1);
        }
    },

    pageNext: function(){
        //Se asociara al evento de pagina siguiente
        var newRange = this.calculateRange(this.viewrangeNow.start + this.options.Step);
        this.loadImageRange(newRange.start , newRange.end, 1);
        if (newRange.start != this.viewrangeNow.start){
            this.viewrangeNow = newRange;
            //this.moveContainer(1);
        }
    },

    moveContainer: function(sentido){
         if (this.viewrangeNow.start == 0){
             this.offset = 0;
             this.container.style.left=0;
             return;
         }
         var newoffset = 0 ;
         for(var i = this.viewrangeNow.start ; i < this.viewrangeNow.end ; i++){
            enlace = this.enlaces[i];
            imagen = enlace.getElement('img');
            newoffset += imagen.getSize().size.x;
         }
         var newleft = this.offset + (sentido * newoffset);
         this.offset = newleft;
         this.container.style.left= -newleft;
    },

/*
Funciona con padding en los top y bottom y margin en los left y right
*/
    loadOneImage: function(indice){
        var zoom = this.options.zoom;
        var cell = this.enlaces[indice];
        var img = new Element("img",{
            'alt': cell.getAttribute("alt"),
            'title': cell.getAttribute('fullname'),
            'src': cell.getAttribute('thumb') + this.options.LoadImagesWith,
            styles: zoom.general,
            events: {
                "mouseover": function() {
                    this.setStyles(zoom.onmouse)
                },
                "mouseleave": function() {
                    this.setStyles(zoom.normal)
                }
            }
        });
        img.injectTop(cell);
        this.imagesloaded[indice]=true;
        return img;
    },


    desactivarImagen: function(){
        this.setStyle('display', "none");
    },

    activarImagen: function(){
        this.setStyle('display',"inline");
    },

    loadImageRangeBucle: function(Rstart, Rend, sentido, i){
        var zoom = this.options.zoom;
        if (i>=Rstart  && i<Rend){
            if (!this.imagesloaded[i]){
                var img = this.loadOneImage(i);
                var efectoin = new Fx.Styles(img, { duration: zoom.delay , transition: zoom.fx });
                efectoin.start({
                    'height': zoom.normal.height,
                    'width': zoom.normal.width
                });
            }
            else {
                var cell = this.enlaces[i];
                var img = cell.getElement('img');
                if(img.getStyle('display') != 'inline'){
                    img.setStyle('display',"inline");
                    var efectoin = new Fx.Styles(img, { duration: zoom.delay , transition: zoom.fx });
                    efectoin.start({
                        'height': zoom.normal.height,
                        'width': zoom.normal.width
                    });
                }
            }
        }
        else {
            if (this.imagesloaded[i]){
                var cell = this.enlaces[i];
                var img = cell.getElement('img');
                if (img.getStyle('display') != 'none'){
                    var efectoout = new Fx.Styles(img, {onComplete: this.desactivarImagen.bind(img), duration: zoom.delay , transition: zoom.fx});
                    efectoout.start({
                        'height': zoom.normal.height,
                        'width': '0px'
                    });
                    }
            }
            else {
                // Esta dentro de un salto despues del rango actual
                //Esta dentro de un salto previo del rango actual , nunca es cero porque i no es cero
                if ( (i >= Rend && i< (Rend + (this.options.Step * 2) )) ||
                    (i < Rstart && i>=(Rstart - (this.options.Step * 2)) )){
                        var img=this.loadOneImage(i);
                        img.setStyle('display',"none");
                }
            }
        }

    },



    loadImageRange: function(Rstart, Rend, sentido){
        /*   Carga las imagenes del rango, para no necesitar cargar
         *   todas las imagenes de golpe durante la carga de pagina
         *   Si ya estaban cargadas no se volveran a cargar
         */
         if (Rstart < Rend && sentido == -1){
            for (var i=0; i<this.ImagesNum; i++){
                this.loadImageRangeBucle(Rstart, Rend, sentido, i);
            }
        }
        if (Rstart < Rend && sentido > -1){
            for (var i=this.ImagesNum-1; i>=0; i--){
                this.loadImageRangeBucle(Rstart, Rend, sentido, i);
            }
        }

    },


    calculateRange: function(index){
        //Calcula el rango de imagenes visibles para index dado
        //index es el nuevo comienzo del rango
        var Rend = index + this.options.ViewRange;
        if (Rend >= this.ImagesNum) {
          $$(this.options.RightButton).addClass('disabled');
        } else {
          $$(this.options.RightButton).removeClass('disabled');
        }

        if (index <= 0) {
          $$(this.options.LeftButton).addClass('disabled');
        } else {
          $$(this.options.LeftButton).removeClass('disabled');
        }

        // Si no newIndex es igual a Index, entonces devolvemos el mismo rango actual
        if (index >= this.ImagesNum || index < 0) {
            return this.viewrangeNow;
        }

        //Si hace falta reajustar el intervalo para que no salga de limites
        if (Rend > this.ImagesNum ) {
            return {
                    start : this.ImagesNum - this.options.ViewRange,
                    end : this.ImagesNum
            };
        }
        return {
               start : index,
               end : Rend
         };
    },

    createEvents: function(){
        $$(this.options.LeftButton).each(function(el){
    			el.addEvent('click', this.pageBack.bind(this));
        }, this);

        $$(this.options.RightButton).each(function(el){
    			el.addEvent('click', this.pageNext.bind(this));
        }, this);
    }
});

Carrusel.implement(new Events); // Implements addEvent(type, fn), fireEvent(type, [args], delay) and removeEvent(type, fn)
Carrusel.implement(new Options);// Implements setOptions(defaults, options)
