var $removeEvents = function (object, type)
{
        if (!object.events) return object;
        if (type){
                if (!object.events[type]) return object;
                for (var fn in object.events[type]) object.removeEvent(type, fn);
                object.events[type] = null;
        } else {
                for (var evType in object.events) object.removeEvents(evType);
                object.events = null;
        }
        return object;
};
                                
var gallery = new Class({
        initialize: function(element, options) {
                this.setOptions({
                        showArrows: true,
                        showCarousel: true,
                        showInfopane: true,
                        thumbHeight: 71,
                        thumbWidth: 71,
                        thumbSpacing: 1,
                        thumbMaxOpacity: 0.99,
                        thumbMinOpacity: 0.55,
                        fadeDuration: 500,
                        delay: 9000,
                        preloader: true,
                        manualData: [],
                        populateData: true,
                        elementSelector: "div.imageElement",
                        titleSelector: "h3",
                        subtitleSelector: "p",
                        imageSelector: "img.full",
                        thumbnailSelector: "img.thumbnail",
                        slideInfoZoneOpacity: 0.99,
                        carouselOpacity: 0.99,
                        destroyAfterPopulate: true,
                        baseClass: 'jdGallery',
                        withArrowsClass: 'withArrows'
                }, options);
                this.fireEvent('onInit');
                this.currentIter = 0;
                this.lastIter = 0;
                this.maxIter = 0;
                this.galleryElement = element;
                this.galleryData = this.options.manualData;
                this.galleryInit = 1;
                this.galleryElements = Array();
                this.thumbnailElements = Array();
                this.galleryElement.addClass(this.options.baseClass);
                if (this.options.populateData)
                        this.populateData();
                element.style.display="block";
                
                this.constructElements();
                if ((data.length>1)&&(this.options.showArrows))
                {
                        var leftArrow = new Element('a').addClass('left').addEvent(
                                'click',
                                this.prevItem.bind(this)
                        ).injectInside(element);
                        
                        var rightArrow = new Element('a').addClass('right').addEvent(
                                'click',
                                this.nextItem.bind(this)
                        ).injectInside(element);
                        this.galleryElement.addClass(this.options.withArrowsClass);
                }
                this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
                if (this.options.showInfopane) this.initInfoSlideshow();
                if (this.options.showCarousel) this.initCarousel();
                this.doSlideShow(1);
        },
        populateData: function() {
                currentArrayPlace = this.galleryData.length;
                options = this.options;
                data = this.galleryData;
                this.galleryElement.getElements(options.elementSelector).each(function(el) {
                        elementDict = {
                                image: el.getElement(options.imageSelector).getProperty('src'),
                                number: currentArrayPlace
                        };
                        if ((options.showInfopane) | (options.showCarousel))
                                Object.extend(elementDict, {
                                        title: el.getElement(options.titleSelector).innerHTML,
                                        description: el.getElement(options.subtitleSelector).innerHTML
                                });
                        if (options.showCarousel)
                                Object.extend(elementDict, {
                                        thumbnail: el.getElement(options.thumbnailSelector).src
                                });
                        
                        data[currentArrayPlace] = elementDict;
                        currentArrayPlace++;
                        if (this.options.destroyAfterPopulate)
                                el.remove();
                });
                this.galleryData = data;
                this.fireEvent('onPopulated');
        },
        constructElements: function() {
                el = this.galleryElement;
                this.maxIter = this.galleryData.length;
                var currentImg;
                for(i=0;i<this.galleryData.length;i++)
                {
                        var currentImg = new Fx.Style(
                                new Element('div').addClass('slideElement').setStyles({
                                        'position':'absolute',
                                        'left':'0px',
                                        'right':'0px',
                                        'margin':'0px',
                                        'padding':'0px',
                                        'backgroundImage':"url('" + this.galleryData[i].image + "')",
                                        'backgroundPosition':"center top",
                                        'opacity':'0'
                                }).injectInside(el),
                                'opacity',
                                {duration: this.options.fadeDuration}
                        );
                        this.galleryElements[parseInt(i)] = currentImg;
                }
        },
        destroySlideShow: function(element) {
                var myClassName = element.className;
                var newElement = new Element('div').addClass('myClassName');
                element.parentNode.replaceChild(newElement, element);
        },
        startSlideShow: function() {
                this.fireEvent('onStart');
                this.loadingElement.style.display = "none";
                this.lastIter = this.maxIter - 1;
                this.currentIter = 0;
                this.galleryInit = 0;
                this.galleryElements[parseInt(this.currentIter)].set(1);
                if (this.options.showInfopane)
                        this.showInfoSlideShow.delay(1000, this);
        },
        nextItem: function() {
                this.fireEvent('onNextCalled');
                this.nextIter = this.currentIter+1;
                if (this.nextIter >= this.maxIter)
                        this.nextIter = 0;
                this.galleryInit = 0;
                this.goTo(this.nextIter);
        },
        prevItem: function() {
                this.fireEvent('onPreviousCalled');
                this.nextIter = this.currentIter-1;
                if (this.nextIter <= -1)
                        this.nextIter = this.maxIter - 1;
                this.galleryInit = 0;
                this.goTo(this.nextIter);
        },
        goTo: function(num) {
                if (this.options.showInfopane)
                {
                        this.slideInfoZone.clearChain();
                        this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
                } else
                        this.changeItem.delay(500, this, num);
                if (this.options.showCarousel)
                        this.clearThumbnailsHighlights();
        },
        changeItem: function(num) {
                this.fireEvent('onStartChanging');
                this.galleryInit = 0;
                if (this.currentIter != num)
                {
                        for(i=0;i<this.maxIter;i++)
                        {
                                if ((i != this.currentIter)) this.galleryElements[i].set(0);
                        }
                        if (num > this.currentIter) this.galleryElements[num].custom(1);
                        else
                        {
                                this.galleryElements[num].set(1);
                                this.galleryElements[this.currentIter].custom(0);
                        }
                        this.currentIter = num;
                }
                this.doSlideShow.bind(this)();
                this.fireEvent('onChanged');
        },
        doSlideShow: function(position) {
                if (this.galleryInit == 1)
                {
                        imgPreloader = new Image();
                        imgPreloader.onload=function(){
                                this.startSlideShow.delay(10, this);
                        }.bind(this);
                        imgPreloader.src = this.galleryData[0].image;
                } else {
                        if (this.options.showInfopane)
                        {
                                if (this.options.showInfopane)
                                {
                                        this.showInfoSlideShow.delay((500 + this.options.fadeDuration), this);
                                } /*else
                                        if (this.options.showCarousel)
                                                this.centerCarouselOn(position);*/
                        }
                }
        },
        initCarousel: function () {
                var carouselContainerElement = new Element('div').addClass('carouselContainer').injectInside(this.galleryElement);
                this.carouselContainer = new Fx.Styles(carouselContainerElement, {transition: Fx.Transitions.expoOut});
                this.carouselContainer.normalHeight = carouselContainerElement.offsetHeight;
                this.carouselContainer.set({'opacity': this.options.carouselOpacity, 'top': 0});
                
                var carouselElement = new Element('div').addClass('carousel').injectInside(carouselContainerElement);
                this.carousel = new Fx.Styles(carouselElement);
                
                this.carouselWrapper = new Element('div').addClass('carouselWrapper').injectInside(this.carousel.element);
                this.carouselInner = new Element('div').addClass('carouselInner').injectInside(this.carouselWrapper);

                this.carouselWrapper.scroller = new Scroller(this.carouselWrapper, {
                        area: 100,
                        velocity: 0.2
                })
                
                this.carouselWrapper.elementScroller = new Fx.Scroll(this.carouselWrapper, {
                        duration: 400,
                        onStart: this.carouselWrapper.scroller.stop.bind(this.carouselWrapper.scroller),
                        onComplete: this.carouselWrapper.scroller.start.bind(this.carouselWrapper.scroller)
                });

                this.constructThumbnails();

                this.carouselInner.style.width = ((this.maxIter * (this.options.thumbWidth + this.options.thumbSpacing)) - this.options.thumbSpacing + this.options.thumbWidth) + "px";
                this.carouselWrapper.scroller.start();
        },
        constructThumbnails: function () {
                element = this.carouselInner;
                for(i=0;i<this.galleryData.length;i++)
                {
                        var currentImg = new Fx.Style(new Element ('div').addClass("thumbnail").setStyles({
                                        backgroundImage: "url('" + this.galleryData[i].thumbnail + "')",
                                        backgroundPosition: "center center",
                                        backgroundRepeat: 'no-repeat',
                                        marginLeft: this.options.thumbSpacing + "px",
                                        width: this.options.thumbWidth + "px",
                                        height: this.options.thumbHeight + "px"
                                }).injectInside(element), "opacity", {duration: 200}).set(this.options.thumbMinOpacity);
                        currentImg.element.addEvents({
                                'mouseover': function (myself) {
                                        myself.clearTimer();
                                        myself.custom(this.options.thumbMaxOpacity);
                                }.pass(currentImg, this),
                                'mouseout': function (myself) {
                                        myself.clearTimer();
                                        myself.custom(this.options.thumbMinOpacity);
                                }.pass(currentImg, this),
                                'click': function (myself) {
                                        this.goTo(myself.relatedImage.number);
                                }.pass(currentImg, this)
                        });
                        
                        currentImg.relatedImage = this.galleryData[i];
                        this.thumbnailElements[parseInt(i)] = currentImg;
                }
        },
        clearThumbnailsHighlights: function()
        {
                for(i=0;i<this.galleryData.length;i++)
                {
                        this.thumbnailElements[i].clearTimer();
                        this.thumbnailElements[i].custom(this.options.thumbMinOpacity);
                }
        },
        centerCarouselOn: function(num) {
                var carouselElement = this.thumbnailElements[num];
                var position = carouselElement.element.offsetLeft + (carouselElement.element.offsetWidth / 2);
                var carouselWidth = this.carouselWrapper.offsetWidth;
                var carouselInnerWidth = this.carouselInner.offsetWidth;
                var diffWidth = carouselWidth / 2;
                var scrollPos = position-diffWidth;
                this.carouselWrapper.elementScroller.scrollTo(scrollPos,0);
        },
        initInfoSlideshow: function() {
                this.slideInfoZone = new Fx.Styles(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
                var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
                var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
                this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
                this.slideInfoZone.element.setStyle('opacity',0);
        },
        changeInfoSlideShow: function()
        {
                this.hideInfoSlideShow.delay(10, this);
                this.showInfoSlideShow.delay(500, this);
        },
        showInfoSlideShow: function() {
                this.fireEvent('onShowInfopane');
                this.slideInfoZone.clearTimer();
                element = this.slideInfoZone.element;
                element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
                element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
                this.slideInfoZone.custom({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
/*                if (this.options.showCarousel)
                        this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));*/
                return this.slideInfoZone;
        },
        hideInfoSlideShow: function() {
                this.fireEvent('onHideInfopane');
                this.slideInfoZone.clearTimer();
                this.slideInfoZone.custom({'opacity': 0, 'height': 0});
                return this.slideInfoZone;
        }
});
gallery.implement(new Events);
gallery.implement(new Options);

