/*
*  @ DynaSlide:	A Slider/Hider component with Ajax support
*  @ version: 	0.46 - Free for personal usage
*  @ Copyright:	Jabis Sevon
*/
/* @ Example usage:
window.addEvent('domready',
function() {
    if ($('DScontainer')) {
        DS = new DynaSlide($('DScontainer'), {
            naviOffset: 900,
            rotation: true,
            menuSelector: '.menu_item',
            slideAction: 'mouseenter'
        });
    }
});
*/
var DynaSlide = new Class({
    Implements: [Options, Events, Chain],
    options: {
        onAutoRotate: Class.empty,
        onBuildMenuAction: Class.empty,
        onDGinit: Class.empty,
        onEvalOverflow: Class.empty,
        onRotate: Class.empty,
        onSlideToItem: Class.empty,
        onStop: Class.empty,
        shadow: false,
        //should we add a shadow (needs some images)
        naviDirection: "horizontal",
        // horizontal = left -> right, vertical = top -> down
        naviOffset: 300,
        //the offset from which and to which the slide goes in pixels
        itemsSelector: ".DS_slide_item",
        //the slide item itself
        menuSelector: ".DS_menu_item",
        //well duh, the menu-items, needs to be one/slide
        scrollNavSelector: ".DS_scroll_item",
        //scrollnav is still heavy under development, don't encourage to use
        titleContainer: "DStitle",
        //for displaying the title of the div
        slideAction: "none",
        // takes events such as mouseenter, click or however you want the slides to operate
        transitionTime: 1500,
        // the time slides take to do the transition
        slideInt: 9000,
        // the interval used to autorotate content
        startIndex: 0,
        // the starting index
        ajax: false,
        //should menu's requests be handled
        evalOver: false,
        //dev
        rotation: false,
        //the autorotation, if enabled, will automatically slide forwards slideInt intervals
        scrollNav: false,
        //scrollnav is still heavy under development, don't encourage to use
        DynaGallery: false,
        //scrollnav is still heavy under development, don't encourage to use
        req: $empty // the request object
    },
    initialize: function(holder, options) {
        this.holder = $(holder);
        if (!this.holder.hasClass('IhasDynaSlide')) {
            this.holder.addClass('IhasDynaSlide');
            this.items = [];
            this.menus = [];
            this.titles = [];
            this.ajaxUrls = [];
            this.titleContainer = $(this.options.titleContainer);
            this.setOptions(options);
            if (this.options.naviDirection == "horizontal") {
                this.navidir = 'left';
            } else {
                this.navidir = 'top';
            }
            //console.log(this.navidir);
            this.naviOffset = this.options.naviOffset;
            this.items = $(holder).getElements(this.options.itemsSelector);
            this.menus = $(document.body).getElements(this.options.menuSelector);
            this.titles = $(document.body).getElements(this.options.menuSelector).get('text');
            //console.log(this.menus);	 
            this.createFx(this.options.startIndex);
            if (this.options.scrollNav) this.scrollDirections = $(document.body).getElements(this.options.scrollNavSelector).get('id');
            if (this.options.ajax) {
                this.ajaxUrls = $(document.body).getElements(this.options.menuSelector).get('rel');
                this.ajaxUrls = this.ajaxUrls.clean();
                //console.log(this.ajaxUrls);	    
                this.req = new Request({
                    method: 'post',
                    evalScripts: 'false',
                    url: escape(this.ajaxUrls[this.options.startIndex]),
                    onSuccess: function(resp) {
                        this.applyContent(resp, this.options.startIndex);
                        this.slideToItem(this.options.startIndex);
                    }.bind(this)
                },
                this).send();
            } else {
                this.slideToItem(this.options.startIndex);
            }
            if (this.options.slideAction != 'none') this.buildMenuAction(this.options.slideAction);
            if (this.options.rotation) this.autorotate();
            if (this.options.shadow) {
                if (Browser.Engine.webkit420) {
                    this.holder.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.8)');
                } else if (!Browser.Engine.trident4) {
                    var shadow = new Element('div', {
                        'class': 'DS-bg-wrap'
                    }).inject(this.holder); ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
                        new Element('div', {
                            'class': 'DS-bg DS-bg-' + dir
                        }).inject(shadow);
                    });
                }
            }

            return this;
        } else return false;
    },

    buildMenuAction: function(action) {
        this.menus.each(function(el, idx) {
            $(el).addEvent(action,
            function(e) {
                e.stop();
                this.itemFx.setOptions(this.itemFx.options, {
                    duration: this.options.transitionTime
                });
                if (this.options.ajax) this.ajaxContent(idx);
                else if (this.currentItem != idx) this.slideToItem(idx);
            }.bind(this));
        },
        this);

        this.fireEvent('onBuildMenuAction', action);
    },
    createFx: function() {
        if (!this.itemFx) this.itemFx = new Fx.Elements(this.items, {
            duration: this.options.transitionTime,
            'link': 'chain'
        });

        if (this.options.naviDirection == "horizontal") {
            this.items.each(function(slide) {
                slide.setStyle('left', this.naviOffset);
            });
        } else {
            this.items.each(function(slide) {
                slide.setStyle('top', -this.naviOffset);
            });

        }
    },
    ajaxContent: function(id) {
        this.req = new Request({
            url: escape(this.ajaxUrls[id]),
            onSuccess: function(resp) {
                this.applyContent(resp, id);
                if (this.currentItem != id) this.slideToItem(id);
            }.bind(this)
        },
        this).send();
    },

    applyContent: function(response, id) {
        this.titleContainer.set('text', this.titles[id]);
        this.items[id].set('html', response);
        if (this.options.evalOver) this.evalOverflow();
        // if(this.options.scrollNav) this.createScrollNav(id);
        if (this.options.DynaGallery) this.DGinit();
    },
    slideToItem: function(itemIndex) {
        // console.log(this.naviOffset);
        var numItems = this.items.length;
        if (itemIndex > this.currentItem && itemIndex != 0) {
            var back = true;
        }
        else if (itemIndex < this.currentItem && itemIndex != (numItems - 1)) {
            var front = true;
        }
        else {
            var fin = [ - this.naviOffset, 0];
        }
        if (itemIndex === this.currentItem) {
            var front = false;
            var back = false;
        }
        if (!front && back) {
            var fin = [ - this.naviOffset, 0];
            var out = [0, this.naviOffset];
        }
        if (!back && front) {
            var fin = [this.naviOffset, 0];
            var out = [0, -this.naviOffset];
        }
        var dir = this.navidir;
        var action = {};
        this.items.each(function(slide, index) {
            // console.log(dir);
            if (dir == 'left') {
                if (index == itemIndex && index != this.currentItem) {
                    action[index.toString()] = {
                        'left': fin,
                        'opacity': 1
                    };
                }
                else {
                    action[index.toString()] = {
                        'left': out,
                        'opacity': 0
                    };
                }
            } else {
                if (index == itemIndex && index != this.currentItem) {
                    action[index.toString()] = {
                        'top': fin,
                        'opacity': 1
                    };
                }
                else {
                    action[index.toString()] = {
                        'top': out,
                        'opacity': 0
                    };
                }
            }
        },
        this);
        this.fireEvent('onSlideToItem', itemIndex);
        this.currentItem = itemIndex;
        this.itemFx.start(action);
        if (this.options.scrollNav) this.createScrollNav(this.currentItem);
    },
    /* test rotation */
    autorotate: function() {
        this.slideshowInt = this.rotate.periodical(this.options.slideInt, this);
        this.fireEvent('onAutoRotate');
    },
    stop: function() {
        clearInterval(this.slideshowInt);
        this.fireEvent('onStop');
    },
    rotate: function() {
        var current = this.currentItem;
        //console.log(current);
        var next = (current + 1 >= this.items.length) ? 0 : current + 1;
        //console.log(next);
        if (this.options.ajax) this.ajaxContent(next);
        else this.slideToItem(next);
        this.fireEvent('onRotate');
    },
    evalOverflow: function() {
        //console.log(cur);
        $$(this.items).each(function(el) {
            el.setStyle('overflow', 'auto');
        }.bind(this));
        this.fireEvent('onEvalOverflow');
    },
    DGinit: function() {
        $$('p.thumbs a').each(function(element) {
            new DynaGallery(element, {
                centered: true,
                closer: false,
                origin: element.getElement('img')
            });
        });
        this.fireEvent('onDGinit');
    },
    createScrollNav: function(id) {
        if (!this.scrollFx) this.scrollFx = new Fx.Morph();
        var myElement = $(this.items[id]);
        var decreaseHeight = myElement.getScrollSize().y;
        var containerHeight = $(this.holder).getScrollSize().y;
        //console.log(myElement.getCoordinates());
        var amount = containerHeight - decreaseHeight;
        $$(this.options.scrollNavSelector).each(function(el) {
            var scrollDir = $(el).get('id');
            var a = $(el).get('rel');
            var startY = $(myElement).getStyle('top');
            //console.log(startY);
            el.addEvent('click',
            function(e) {
                e.stop();
                var curY = $(myElement).getStyle('top');
                //console.log(curY);
                if (a != "none") amount = a;
                if (scrollDir == "scrolldown") {
                    var act = {
                        'top': [curY, -amount]
                    };
                }
                else if (scrollDir == "scrollup") {
                    var act = {
                        'top': [curY, startY]
                    };
                }
                myElement.morph(act);
            });
        }.bind(this));
    }

});

var DS0 = null;
var DS1 = null;