// Font replacement
Cufon.replace('.label h3', {fontFamily: 'AGaramond RegularSC'});

Cufon.replace('h2.title, h3.callout, .link-callout h3, .list-callout h3, .upcoming-wines h3',
    {fontFamily: 'TradeGothic LT CondEighteen'});
Cufon.replace('.quote p, form:not(.filter-form) label, .contact-us .phone', 
    {fontFamily: 'TradeGothic LT CondEighteen'});
Cufon.replace('.sash-text h3', 
    {textShadow: '#777 1px 1px', fontFamily: 'TradeGothic LT CondEighteen'});


Ext.ns('Lb');

Lb.fadeDuration = 0.5;
Lb.captionFadeOpacity = 0.85;
Lb.dh = Ext.DomHelper;

Lb.amsShopUrl = 'https://shop.lambertbridge.com/ADDITEM.AMS';

Lb.fadeOutCaption = function()
{
    var captionWrapper = Ext.select('.caption-wrapper');
    captionWrapper.fadeOut({
        duration: this.fadeDuration
    });
};

Lb.setCaption = function(slide)
{
    var caption = slide.child('img.photo:first-child', true).title.replace(/_/g, ' ');
    var credit = slide.child('img.photo:first-child', true).getAttribute('credit');

    var captionWrapper = Ext.get('mainGalleryWrapper').select('.caption-wrapper');
    if (caption == '' && credit == '') {
        this.fadeOutCaption();
        return;
    }

    Ext.select('#mainGalleryWrapper .caption-wrapper p.caption').update(caption);
    Ext.select('#mainGalleryWrapper .caption-wrapper p.credit').update(credit);
    captionWrapper.fadeIn({
        duration: this.fadeDuration,
        endOpacity: this.captionFadeOpacity
    });
};

Lb.setupVineyardDetails = function()
{
    var fadeIn = function() {
        // Pause old gallery
        if (this.currentVineyardGallery) this.currentVineyardGallery.pause();
        // fade in new details
        this.currentVineyardName = getVineyardNameFromAnchor();
        this.currentVineyard = Ext.get('vineyard-' + this.currentVineyardName).fadeIn({useDisplay: true});
        // play if there is a gallery
        var gallery = this.vineyardGalleries['vineyard-gallery-' + this.currentVineyardName];
        if (gallery) {
            this.currentVineyardGallery = gallery.play();
        }
    }.createDelegate(this);
    
    var fadeOut = function() {
        if (this.currentVineyardGallery) {
            this.currentVineyardGallery.pause();
        }
        this.currentVineyard.fadeOut({duration: 0.2, callback: fadeIn, useDisplay: true});
    }.createDelegate(this);

    var getVineyardNameFromAnchor = function() {
        var urlparts = window.location.href.split('#');
        if (urlparts.length > 1) {
            var vineyardName = urlparts.pop();
        } 
        if (vineyardName && vineyardName.length > 0) {
            return vineyardName;
        }
        
        return false;
    };
    
    var getCurrentVineyardEl = function() {
        if (this.currentVineyardName) {
            return Ext.get('vineyard-'+this.currentVineyardName);
        } else {
            return Ext.fly('vineyard-details').down('.item');
        }
    }.createDelegate(this);


    this.currentVineyard;
    this.currentVineyardGallery;
    this.currentVineyardName;
        
    // Setup itial vineyard
    this.currentVineyardName = getVineyardNameFromAnchor();
    this.currentVineyard = getCurrentVineyardEl();
    if (!this.currentVineyardName) {
        this.currentVineyardName = this.currentVineyard.id.substr(9);
    }

    // Show vineyard
    this.currentVineyard.show();
    // play gallery if one exists
    this.currentVineyardGallery = this.vineyardGalleries['vineyard-gallery-' + this.currentVineyardName];
    if (this.currentVineyardGallery) {
        this.currentVineyardGallery.play();
    }

    var onViewVineyardClick = function(evt, target) {
        // pageTracker._trackEvent('VineyardMap', action, optional_label, optional_value);
        // pageTracker._trackPageview('/winery/vineyards/' + this.currentVineyardName)
        pageTracker._trackPageview(window.location.href);
        fadeOut();
    }.createDelegate(this);;
    Ext.select('a.view-vineyard, #vineyard-map area').on('click', onViewVineyardClick);
};

Lb.setupTeamQuotesAndBios = function()
{
    this.quoteGallery = new Ext.ux.Carousel('quotes', {
        itemSelector: 'div.item',
        autoPlay: true,
        interval: 6,
        wrap: true,
        hideNavigation: true,
        transitionType: 'fade',
        freezeOnHover: true
    });

    Ext.select('a.hide-bio').on('click', function(evt, target) {
        evt.preventDefault();
        
        var that = this;
        Ext.fly('team-bios').fadeOut({useDisplay: true, callback: function(el) {
            that.quoteGallery.play();
            that.currentBio.setVisible(false);
            Ext.fly('random-quotes').fadeIn({useDisplay: true});
        }});
    }, this);

    Ext.select('a.view-bio, #team-map area').on('click', function(evt, target) {
        evt.preventDefault();

        var that = this;
        var fadeInBio = function(el) {
            Ext.fly('team-bios').setVisible(true);
            that.currentBio = Ext.get('bio-' + bioName).fadeIn({useDisplay: true});
        };
        var fadeOutBio = function() {
            that.currentBio.fadeOut({duration: 0.2, callback: fadeInBio});
        };

        // Pull name from anchor
        var bioName = target.href.split('#').pop();
        
        if (this.quoteGallery.playing) {
            this.quoteGallery.pause();
            Ext.fly('random-quotes').fadeOut({useDisplay: true, callback: fadeInBio});
        } else if (this.currentBio) {
            fadeOutBio();
        };
    }, this);
};

Lb.setupVineyardGalleries = function() {
    // Init galleries
    this.vineyardGalleries = this.vineyardGalleries || {};
    
    Ext.select('.photo-gallery.vineyards').each(function(el) {
        if (Ext.get(el).select('img.photo').elements.length <= 1) return;
        
        var vineyardGalleryId = el.id;
        var vineyardGallery = new Ext.ux.Carousel(vineyardGalleryId, {
            itemSelector: 'img.photo',
            autoPlay: false,
            interval: 3,
            wrap: true,
            hideNavigation: true,
            transitionType: 'fade',
            freezeOnHover: false,
            showPlayButton: false
        });
        this.vineyardGalleries[vineyardGalleryId] = vineyardGallery;
    }, this);
};

Lb.setupMainGallery = function()
{
    // Init galleries
    this.mainGallery = new Ext.ux.Carousel('mainGallery', {
        itemSelector: 'img.photo',
        autoPlay: true,
        interval: 5,
        wrap: true,
        hideNavigation: true,
        transitionType: 'fade',
        freezeOnHover: true
    });
    // Set first caption
    this.setCaption(this.mainGallery.slides[this.mainGallery.activeSlide]);
    Ext.select('.gallery-controls').show();
    Ext.fly('mainGalleryWrapper').select('.pagination').show();

    // Use our own pagination controls
    Ext.select('.pagination.next-photo, .gallery-controls .next-arrow')
        .on('click', function(evt){evt.preventDefault(); this.mainGallery.next(); }, this);
    Ext.select('.pagination.prev-photo, .gallery-controls .prev-arrow')
        .on('click', function(evt){evt.preventDefault(); this.mainGallery.prev(); }, this);
        
    Ext.select('.gallery-controls .next-photo').update(this.mainGallery.slides.length);
    
    // Fade and set caption and credits on change
    this.mainGallery.on('change', function(slide, index)
    {
        Ext.select('.gallery-controls .prev-photo').update(index+1);
        this.fadeOutCaption();
    }, this);
    this.mainGallery.on('fadeComplete', function(slide, index)
    {
        this.setCaption(slide);
    }, this);
};

Lb.styleHacks = function()
{
    // Add first and last classes to all ul elements
    Ext.select('ul li:first-child, .shipments .yui-u ul:first-child').addClass('first');
    Ext.select('ul li:last-child').addClass('last');
    Ext.select('.shipments .yui-u ul:last-child').addClass('last');

    // Add split5 class to content-subnav if there are 5 elements
    Ext.select('.content-subnav ul').first().each(function(el) {
        var subNavLength = el.select('li').elements.length;
        if (4 < subNavLength) {
            el.addClass('split'+subNavLength);
        }
    });
    
    if (Ext.select('body').hasClass('current-releases')) {
        // Wrap upcoming-wines rows to control height
        var numColumns = 3;
        var upcomingWines = Ext.query('ul.upcoming-wines');
        sliceRounds = Math.floor(upcomingWines.length / numColumns);
        for (var i=0; i<sliceRounds; i++) {
            var row = upcomingWines.slice(i*numColumns, (i+1)*numColumns);
            // var div = this.dh.insertBefore(row[0], {tag: 'div', cls: 'upcoming-wines-wrapper', cn: row});
            var div = this.dh.insertBefore(row[0], {tag: 'div', cls: 'upcoming-wines-wrapper'});
            for (var j=row.length; j>-1; --j) {
                Ext.get(div).insertFirst(row[j]);
            }
        }
    }
};

Lb.events = function(sectionName)
{
    var HintInput = function HintInput(){};
    HintInput.prototype.onFocus = function(evt, target)
    {
        if (target.value != this.origHintValue) return;
        target.value = '';
    };
    HintInput.prototype.onBlur = function(evt, target)
    {
        if ('' != target.value) return;
        target.value = this.origHintValue;
    };
    
    // Text input hints
    var hintInput = new HintInput();
    
    Ext.select('form input[type=text].hint').each(function(el) {
        hintInput.origHintValue = el.getValue();
        el.on('focus', hintInput.onFocus, hintInput);
        el.on('blur', hintInput.onBlur, hintInput);
    });

    if (Ext.getBody().hasClass('visit')) {    
        var drivingForm = Ext.get('drivingDirectionsForm');
        drivingForm.on('submit', function(evt, target) {
            evt.preventDefault();
            var destAddress = '4085+West+Dry+Creek+Road,+Healdsburg,+CA+95448-9117+(Lambert+Bridge+Winery)';
            var sourceAddress = Ext.get(target).down('input[type=text]').getValue();
            window.open('http://maps.google.com/maps?f=d&source=s_d&saddr=' + sourceAddress + '&daddr=' + destAddress +'&hl=en&');
        }, this);
    }
    
    // Catch Event type filters and redirect to event filtering URL
    var filterEvents = Ext.get('filterEvents');
    if (filterEvents) {
        filterEvents.on('change', function(evt, target)
        {
            window.location.href = Ext.get(target).getValue();
        });
    }
    
    // Search field hint
    // var hintInput = new HintInput();
    // hintInput.origHintValue = Ext.fly('searchInput').getValue();
    // var inputField = Ext.fly('searchInput');
    // inputField.on('focus', hintInput.onFocus, hintInput);
    // inputField.on('blur', hintInput.onBlur, hintInput);
    
};

Lb.setSelectedFilter = function(filter) {
    if (Ext.get(filter)) {
        var form = Ext.get(filter);
        var eventFilterName = window.location.href.replace(/\/$/,"").split('/').pop();
        form.select('option').each(function(el) {
            if (el.getValue() == eventFilterName) {
                el.set({selected: 'selected'});
            }
        });
    }
};

Ext.onReady(function()
{
    
    Lb.styleHacks();
    Lb.events();
    
    // Put external links to a new window
    Ext.select('a[href^="http://"]').set({"target": "_blank"});
    
    // Print page
    Ext.select('a.print').on('click', function(evt, t) {
        evt.preventDefault();
        window.print();
    });

    // Find selected filter
    Lb.setSelectedFilter('eventFilterForm');
    Lb.setSelectedFilter('stateFilterForm');
    Lb.setSelectedFilter('recipeVarietalFilterForm');

    // Init the rotating quotes and hook up links for bio swap
    var quotes = Ext.get('quotes');
    if (quotes) {
        Lb.setupTeamQuotesAndBios();
    }

    // var filterFormSelectHandler = function(select) {
    //     Ext.fly('filterState').on('change', function(evt, target) {
    //         if (target.value == '0') return;
    //         window.location.href = '/wines/wine-finder/' + target.value;
    //     });
    // };
    // Hnadlers for the filter forms
    if (Ext.getBody().hasClass('recipes')) {
        Ext.fly('filterRecipeByVarietal').on('change', function(evt, target) {
            if (target.value == '0') return;
            window.location.href = '/wines/recipes/varietal/' + target.value;
        });
    }
    if (Ext.getBody().hasClass('wine-finder')) {
        Ext.fly('filterState').on('change', function(evt, target) {
            if (target.value == '0') return;
            window.location.href = '/wines/wine-finder/' + target.value;
        });
    }
    if (Ext.getBody().hasClass('events') && Ext.fly('filterCategory')) {
        Ext.fly('filterCategory').on('change', function(evt, target) {
            if (target.value == '0') return;
            window.location.href = '/events/' + target.value;
        });
    }

    if (Ext.getBody().hasClass('vineyards')) {
        Lb.setupVineyardGalleries();
        Lb.setupVineyardDetails();
    }

    // Setup gallery controls if we have more than 1 image
    var mainGallery = Ext.get('mainGallery');
    if (mainGallery) {
        var numGalleryImages = mainGallery.select('img.photo').elements.length;
        if (numGalleryImages > 1) {
            Lb.setupMainGallery();
        } else if (1 == numGalleryImages) {
            // Set first caption if it exists
            Lb.setCaption(mainGallery);
        }
    }
});

