Ext.ns('Tsf.site');

Tsf.site.WorkSlides = Ext.extend(Tsf.site.Slides, {
    // Config

    constructor: function(elId, config) {
        config = config || {};
        Ext.apply(this, config);
        
        // Find the first project
        this.initialStep = Ext.get(elId).select('.projects .project').first().id;

        Tsf.site.WorkSlides.superclass.constructor.call(this, elId, config);
    },
    
    initMarkup: function() {
        this.stageImage = Ext.get('stage-image').hide();
        this.stage = Ext.get('stage-project');
        this.preloader = this.stage.first('img.preloader').hide();
        this.navigation = this.stage.child('.navigation').hide();
        
        // Init carousel
        this.mainGallery = new Ext.ux.Carousel('stage-image', {
            itemSelector: '.images img',
            autoPlay: false,
            // transitionDuration: .8,
            interval: 5,
            wrap: true,
            hideNavigation: true,
            transitionType: 'fade',
            freezeOnHover: false
        });
        
        var projects = this.el.select('.project');
        // Add overlay to each thumb
        var w = this.el.select('.project').first('.thumb').getWidth();
        var h = this.el.select('.project').first('.thumb').getHeight();
        projects.each(function(el) {
            var projectEl = Ext.get(el);
            // projectEl.wrap({tag: 'a', "href": '#project'});
            projectEl.createChild({cls:'overlay'})
                .setStyle({
                    position: 'absolute',
                    top: 0,
                    backgroundColor: '#eaeaea',
                    cursor: 'pointer'
                })
                .setWidth(w)
                .setHeight(h)
                .setOpacity(0.65);
        });
        // this.el.child('.project.active .overlay').setOpacity(0);
        
        // Fill the empty project space for that row
        var numProjects = projects.getCount();
        var numRows = Math.ceil(numProjects / 4);
        var numEmptyProjectThumbs = numRows*4 % projects.getCount();
        for (var i=0; i < numEmptyProjectThumbs; i++) {
            this.el.select('.projects').createChild({cls: 'project empty'});
        }
    },
    
    initEvents: function() {
        // Keyboard nav on work-slides
        Ext.EventManager.on(document, "keypress", this.onKeyboardEvent, this);

        // Description drawer
        this.el.child('.description .expand a')
        .on('click', function(evt, t) {
            evt.preventDefault();
            var target = Ext.get(t);
            this.toggleDescription();
            // var copyEl = this.el.child('.description .copy');
            // copyEl.setOpactiy(0);
            // var w = copyEl.setWidth(copyEl.getWidth()*.8);
            // var h = copyEl.setHeight(copyEl.getHeight()*.8);
            // copyEl.show(true).shift({ 
            //     anchor: 'tr',
            //     width: w,
            //     height: h,
            //     opacity: 1.0
            // });
        }, this);
        
        this.el.child('.navigation')
        .on('click', this.onGalleryNavigationClick, this);
        
        // Thumbnail events
        this.el.select('.project:not(.empty)')
            .hover(this.onProjectMouseEnter, this.onProjectMouseLeave, {scope: this, target: '.project'})
            .on('click', this.onProjectClick, this);
        
        Ext.fly('ft').select('.work ul a')
            .on('click', function(evt, t) { this.scrollToProjectHeader(); }, this);
    },
    
    onKeyboardEvent: function(evt, t) {
        var k = evt.getKey();
        if (k == evt.LEFT) {
            this.mainGallery.prev();
        } else if (k == evt.RIGHT) {
            this.mainGallery.next();
        }
    },
    
    onGalleryNavigationClick: function(evt, t) {
        this.toggleDescription(true);
        var target = Ext.get(t);
        if (target.hasClass('next')) {
            this.mainGallery.next();
        } else if (target.hasClass('prev')) {
            this.mainGallery.prev();
        }
    },
    
    onProjectMouseEnter: function(evt, t) {
        var parent = Ext.get(t).findParent('.project', 5, true);
        if (parent.hasClass('active')) return;
        parent.child('.overlay').fadeOut({duration: 0.15});
        // Ext.get(target).fadeIn({duration: 0.15});
    },

    onProjectMouseLeave: function(evt, t) {
        var parent = Ext.get(t).findParent('.project', 5, true);
        if (parent.hasClass('active')) return;
        parent.child('.overlay').fadeIn({duration: 0.25, endOpacity: 0.65});
        // Ext.get(target).fadeOut({duration: 0.15});
    },
    
    onProjectClick: function(evt, t) {
        var target = Ext.get(t);
        // Hide description
        this.toggleDescription(true);
        var thumb = target.findParent('.project', 50, true);
        // History
        var step = thumb.id;
        Ext.History.add(this.historyName + this.tokenDelimiter + step);
        
        this.scrollToProjectHeader();
    },
    
    onHistoryChange: function(token) {
        
        // Get index from bookmarked state
        var index = 0;
        if (token) {
            var projectName = token.split(this.tokenDelimiter)[1];
            index = this.getIndexFromModel(projectName);
        }
        this.setDocumentTitle(index);
        this.setStep(index);
    },
    
    trackView: function() {
        if (Ext.isDefined(pageTracker)) {
            pageTracker._trackPageview("/work/projects/" + this.activeStep.stepName);
        } 
    },

    add: function(el, index) {
        var stepName = el.parent().id;
        var imagePaths = [];
        el.select('.image').each(function(el) {
            var src = el.getAttribute('data-image');
            imagePaths.push(src);
        });
        // Set model data
        var item = {};
        item.stepName = stepName;
        item.client = el.child('.client').dom.innerHTML;
        item.name = el.child('.name').dom.innerHTML;
        item.description = el.child('.description').dom.innerHTML;
        item.services = el.child('.services').dom.textContent;
        item.images = imagePaths;

        // Create an inex for bookmark history
        this.model.items.push(item);
        this.model.indices[stepName] = index;
    },
    
    setupStage: function(data) {
        this.stageData = data;
        
        this.toggleActiveThumb(Ext.get(data.stepName));
        // Ext.get(data.stepName).radioClass('active');
        
        this.stage.child('.client', true).innerHTML = data.client;
        // this.stage.child('.name', true).innerHTML = data.name;
        this.stage.child('.copy', true).innerHTML = data.description;
        // Ext.get(this.mainGallery.el)
        //     .hide({scope: this, callback: function() {
        //         this.mainGallery.clear();
        //     }
        // });
        // this.stageImage.hide({
        //     scope: this, 
        //     useDisplay: false,
        //     callback: function() {
        //         this.mainGallery.clear();
        //     }
        // });
        
        this.mainGallery.clear();

        var cnt = 0;
        Ext.each(data.images, function(path) {
            var img = this.stageImage.child('.images').createChild({
                tag: 'img',
                src: path
            });
            this.mainGallery.add(img);
            // Setup fade and preloader for first image only
            if (cnt == 0) {
                this.firstProjectImage = img;
            }
            cnt++;
        }, this);
        
        Cufon.refresh('#stage-project h1');
    },
    
    animateStage: function() {
        this.preloader.show(true);
        this.firstProjectImage.on('load', function(evt, t) {
            this.preloader.hide();
            this.navigation.show();
            // Ext.get(this.mainGallery.el).show();
            this.mainGallery.refresh();
            this.stageImage.show({duration: 0.75});
        }, this, {single: true});
    },
    
    scrollToProjectHeader: function() {
        // Scroll to top
        var y = Ext.get('stage-project').getAnchorXY()[1] - 10;
        Ext.select('html,body').scrollTo('top', y, true);
    },
    
    setDocumentTitle: function(index) {
        return document.title = 'Work - ' + this.model.items[index].client + ' - The Superformula';
    },
    
    toggleActiveThumb: function(currentThumb) {
        // var previousOverlay = this.el.child('.project.active');
        // if (previousOverlay) {
        //     previousOverlay.relayEvent('mouseleave', this)
        // }

        var previousOverlay = this.el.child('.project.active .overlay');
        if (previousOverlay) {
            previousOverlay.fadeIn({duration: 0.25, endOpacity: 0.65});
        }
        
        currentThumb.child('.overlay').hide();
        currentThumb.radioClass('active');
    },
    
    toggleDescription: function(forceClose) {
        var target = this.el.child('.description .expand a');
        // Don't bother if it's already closed
        if (forceClose && !target.hasClass('is-open')) {
            return;
        }
        
        target.toggleClass('is-open');
        if (target.hasClass('is-open')) {
            target.dom.innerHTML = 'close';
        } else {
            target.dom.innerHTML = 'see project description';
        }
        this.el.child('.description .copy').toggle();
    }
});
