/**
 *
 * Client Scroller Class v1.1 (Mootools)
 *
 */

Fx.Scroll.Client = new Class({

    Extends: Fx.Scroll,

    options: {
        //custom options
        pageSelector: null,
        infoSelector: null,
        pageCircleContainer: null,
        nextBtn: null,
        infoBtn: null,
        pageBorder: 1,
        flipMidPoint: 300,
        //Fx.Scroll options
        wait: false,
        wheelStops: true,
        link: 'chain',
        duration: 550,
        hashPathRegex: /#([\w-]+)$/i,
        hashLoadDelay: 200
    },

    initialize: function(element, options) {

        //super
        this.parent(element, options);

        //defaults
        this.currPageIndex = 0;

        //setup
        this._cacheElements();
        this._detectBrowser();
        this._stylePageContainerPages();
        this._createPageIndicators();
        this._initEvents();
        this.detectUrlHashPath();

        //init page indicators to 1st page
        this._togglePageIndicator(this.currPageIndex);

        //align first info panel
        this._alignInfoPanel();
    },

    detectUrlHashPath: function(url){
        if (url) {
            var sectionHash = url;
        } else {
            var sectionHash = document.location.hash;
        }
        try {
            var elem = $(sectionHash.match(this.options.hashPathRegex)[1]);
            if (elem) {
                this.gotoSliderPage.delay(this.options.hashLoadDelay, this, elem);
            }
        } catch (err) {}
    },

    _cacheElements: function() {
        if (!this.element || !this.options.pageSelector) {
            return this;
        }
        this.pages = this.element.getElements(this.options.pageSelector);
        return this;
    },

    _detectBrowser: function() {
        //browser detect
        if (RegExp(" AppleWebKit/").test(navigator.userAgent)) {
            this._hasWebkit = true;
            this._sleepTime = 1000; //matches -webkit-transition-duration: 1s
        }
        if (Browser.Platform.ios || Browser.Platform.android || Browser.Platform.webos) {
            this._isMobile = true;
        }
        //only desktop mac (w/ quicktime) supports 3d transform
        if (Browser.Platform.mac && !Browser.chrome && this._hasWebkit && !this._isMobile) {
            this._hasNewWebkit = true;
        }
        return this;
    },

    _stylePageContainerPages: function() {
        //horizontal only
        this.element.setStyles({
            position: 'relative',
            overflow: 'hidden'
        });

        this._elementWidth = this.element.getStyle('width').toInt();
        this._elementHeight = this.element.getStyle('height').toInt();

        this.pages.each(function(page, i){
            page.setStyles({
                overflow: 'hidden',
                position: 'absolute',
                height: this._elementHeight + 'px',
                width: this._elementWidth + 'px',
                top: 0,
                left: (i * this._elementWidth) + (i * this.options.pageBorder) + 'px',
                borderLeft: this.options.pageBorder + 'px',
                borderRight: this.options.pageBorder + 'px',
                borderColor: 'transparent',
                zIndex: 999
            });
        }, this);
        return this;
    },

    _createPageIndicators: function() {
        if (this.options.pageCircleContainer) {
            var pc = $(this.options.pageCircleContainer);
            this.pages.each(function(page, i) {
                var div = document.createElement('div');
                div.className = 'page-circle';
                pc.appendChild(div);
            });
            this.indicators = $(this.options.pageCircleContainer).getChildren();
            this.indicators.addEvent('click', this._handleIndicatorClick.pass(null, this));
        }
        return this;
    },

    _initEvents: function() {
        //container event (same as info click)
        if (this.element) {
            $(this.element).addEvent('click', this._handleInfoClick.pass(null, this));
        }
        //info button event
        if (this.options.nextBtn) {
            $(this.options.infoBtn).addEvent('click', this._handleInfoClick.pass(null, this));
        }
        //next button event
        if (this.options.nextBtn) {
            $(this.options.nextBtn).addEvent('click', this.nextPage.pass(null, this));
        }
        return this;
    },

    _handleInfoClick: function() {
        if (this._hasNewWebkit) {
            return this._flipOldWebkit();
        } else if (this._hasWebkit && !this._hasNewWebkit) {
            return this._flipOldWebkit();
        } else {
            return this._fade();
        }
        return this; //never reached
    },

    _handleIndicatorClick: function(element) {
        if (this.isFlipped) { //flip back, then move ahead
            this._handleInfoClick();
            setTimeout(this._doIndicatorClickTimer.bind(this, element.target), this._sleepTime);
        } else { //just move ahead
            this.gotoPage(this.indicators.indexOf(element.target));
        }
        return this;
    },

    /**
     * Backface compatible browsers do CSS3 3d transition
     */
    _flipNewWebkit: function() {
        if (this._alignInfoPanel()) { //has info panel
            $(this.element).toggleClass('flipped');
            this._toggleIsFlipped();
        }
        return this;
    },

    /**
     * Change non-backface compatible browsers on a timer instead
     */
    _flipOldWebkit: function() {
        if (this._alignInfoPanel()) {
            if (!this.isFlipped) { //flip it
                setTimeout(function(o) {
                    o.currInfoPanel.setStyle('display', 'block');
                }, this.options.flipMidPoint, this);
                setTimeout(function(o) {
                    o.pages[o.currPageIndex].setStyle('display', 'none');
                }, this.options.flipMidPoint, this);
            } else { //unflip it
                setTimeout(function(o) {
                    o.currInfoPanel.setStyle('display', 'none');
                }, this.options.flipMidPoint, this);
                setTimeout(function(o) {
                    o.pages[o.currPageIndex].setStyle('display', 'block');
                }, this.options.flipMidPoint, this);
            }
            $(this.element).toggleClass('flipped');
            this._toggleIsFlipped();
        }
        return this;
    },

    /**
     * For non webkit browsers
     */
    _fade: function() {
        if (this._alignInfoPanel()) { //has info panel
            var thisPage = this.pages[this.currPageIndex];
            thisPage.setStyle('z-index', 2);
            this.currInfoPanel.setStyle('z-index', 1);
            thisPage.fade('toggle');
            this._toggleIsFlipped();
        }
        return this;
    },

    /**
     * Hide all info panels, and align current info panel to 0,0
     */
    _alignInfoPanel: function() {
        //hide all info panels first
        this.element.getElements(this.options.infoSelector).setStyle('display', 'none');

        //align this pages info panel to first position
        var infoPanel = this.pages[this.currPageIndex].getNext(this.options.infoSelector);
        if (infoPanel) {
            var infoDisplay = 'block';
            if (this._hasWebkit && !this._hasNewWebkit && !this.isFlipped) { //for 2d transition
                infoDisplay = 'none';
            }
            infoPanel.setStyles({
                display: infoDisplay,
                position: 'absolute',
                top: 0,
                left: (this.currPageIndex * (this._elementWidth + (this.options.pageBorder))),
                borderLeft: this.options.pageBorder + 'px',
                borderRight: this.options.pageBorder + 'px',
                borderColor: 'transparent',
                zIndex: 1
            });
            this.currInfoPanel = infoPanel;
            return this;
        }
        return false;
    },

    _toggleIsFlipped: function() {
        this.isFlipped = (this.isFlipped) ? false: true;
        $(this.options.infoBtn).toggleClass('selected');
        return this;
    },

    _togglePageIndicator: function(pageNum) {
        this.indicators.removeClass('selected');
        this.indicators[pageNum].addClass('selected');
        return this;
    },

    _doIndicatorClickTimer: function(element) {
        this.gotoPage(this.indicators.indexOf(element));
        return this;
    },

    _doNextClickTimer: function() {
        this.currPageIndex++;
        this.gotoPage(this.currPageIndex);
        return this;
    },

    nextPage: function() {
        if (this.isFlipped) { //flip back then move ahead
            this._handleInfoClick();
            setTimeout(this._doNextClickTimer.bind(this), this._sleepTime);
        } else { //just move ahead
            this.currPageIndex++;
            this.gotoPage(this.currPageIndex);
        }
        return this;
    },

    gotoPage: function(page) {
        this.currPageIndex = page % this.pages.length;
        if (this.currPageIndex == 0) {
            /*
            this.toElement(this.pages[this.currPageIndex], 'x').chain(function(){
                this.set(0,0); //force Firefox to go to 0,0!
            });
            */
            this.start(0,0).chain(function(){
                this.set(0,0); //force Firefox to go to 0,0!
            });
        } else {

            var x = this.pages[this.currPageIndex].getStyle('left').toInt();
            //this.toElement(this.pages[this.currPageIndex], 'x');
            this.start(x,0);
        }
        this._togglePageIndicator(this.currPageIndex);
        return this;
    },

    gotoSliderPage: function(page) {
        for(i = 0; i < this.pages.length; i++){
            if(this.pages[i] == page){
                this.currPageIndex = i;
                break;
            }
        }
        this.gotoPage(this.currPageIndex);
        return this;
    },

    getCurrent: function() {
        return this.pages[this.currentPageIndex];
    }
});

