// JavaScript Document
var GTBase = {
  Version: '0.1'
};

var DropDown = Class.create({
    initialize : function(dropdown, trigger, anchor) {
        //console.log('init');
        this.dropdown = dropdown;
        this.trigger = trigger;
        this.anchor = anchor;
        this.b_show = this.show.bindAsEventListener(this);
        this.b_hide = this.hide.bindAsEventListener(this);
        this.b_peek = this.peek.bindAsEventListener(this);
        this.b_unpeek = this.unpeek.bindAsEventListener(this);
    },
    
    hide : function(e) {
        //console.log('hide');
        if (e) { Event.stop(e); }
        Effect.BlindUp(this.dropdown, { duration: .5, afterFinish: function() {
                this.cleanup();
            }.bind(this)}
        );
        try { $(this.trigger).blur(); }
        catch(err) { }
    },

    show : function(e) {
        //console.log('show');
        Event.stop(e);
        if (!$(this.dropdown).visible() || Element.hasClassName(this.dropdown, 'peek')) {
            $(this.dropdown).hide();
            $(this.dropdown).removeClassName('peek');
            Event.stopObserving($(this.trigger), 'mouseout', this.b_unpeek);
            try { $(this.trigger).blur(); }
            catch(err) { }
            Effect.BlindDown(this.dropdown, { duration: .5, afterFinish: function() {
                    this.invert();
                }.bind(this)}
            );
        }
    },

    peek : function() {
        //console.log('peek');
        if (!$(this.dropdown).visible()) {
            $(this.dropdown).style.overflow = 'hidden';
            $(this.dropdown).addClassName('peek');
            $(this.dropdown).show();
        }
    },

    unpeek : function() {
        //console.log('unpeek');
        $(this.dropdown).hide();
        $(this.dropdown).removeClassName('peek');
    },

    cleanup : function() {
        //console.log('cleanup');
        $(this.trigger).observe('mouseout', this.b_unpeek);
        $(this.anchor).observe('click', this.b_show);
        $(this.anchor).stopObserving('click', this.b_hide);
    },

    invert : function() {
        //console.log('invert');
        $(this.anchor).stopObserving('click', this.b_show);
        $(this.anchor).observe('click', this.b_hide);
    }
});

var FeatureRotator = Class.create({
    // TODO: support for arbitrary number of features

    Index : location.href.slice(location.href.indexOf('?')).toQueryParams().n || 0,
    Counter : 0,
    
    initialize : function(target, indicators, generator, interval) {
        //console.log('initialize');
        this.target = target;
        this.indicators = indicators;
        this.generator = generator;
        this.interval = interval;
        this.pe;
        this.featureStack = [];
        this.indicatorStack = [];
        this.populateStack();
        this.indicatorStack[0].src = '/images/' + this.indicators + 'Progress.gif';
        this.start();
    },
    
    populateStack : function() {
        //console.log('populateStack');
        this.indicatorStack = $A($(this.indicators).getElementsByTagName('img'));
        for (i = 0; i < 5; i++) { this.requestFeature(i); }
   },
    
    requestFeature : function(i) {
        //console.log('requestFeature');
        new Ajax.Request('/inc/' + this.generator + '?n=' + i + '&JSON=1',
            {
                method:'get',
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    if (response.isJSON()) {
                        response = response.evalJSON();
                        this.featureStack[i] = response;
                        preloadImages(response.feature.image);
                    }
                }.bind(this)
            }
        );
    },
    
    start : function() {
        //console.log('start');
        this.pe = new PeriodicalExecuter(this.displayNextFeature.bind(this), this.interval);
    },
    
    displayNextFeature : function() {
        //console.log('displayNextFeature');
        if (this.featureStack[(parseInt(this.Index) + 1) % 5]) {
            this.indicatorStack[this.Index].src = '/images/' + this.indicators + 'Next.gif';
            this.indicatorStack[(parseInt(this.Index) + 1) % 5].src = '/images/' + this.indicators + 'Progress.gif';
        
            this.Index++;
            this.Index = this.Index % 5;

            var oldImage = $(this.target).getElementsByTagName('img')[0];
            var newImage = this.featureStack[this.Index].feature.image;
            Effect.Fade(oldImage, { afterFinish: function() {
                    oldImage.src = this.featureStack[this.Index].feature.image;
                    Effect.Appear(oldImage);
                }.bind(this)}
            );

            type = newImage.slice(1, newImage.indexOf('/', 1));
            id = newImage.slice(newImage.lastIndexOf('/') + 2);

            oldImage.parentNode.href = '/' + type + '/release.html?id=' + id;
            oldImage.alt = this.featureStack[this.Index].feature.head;
            $(this.target).getElementsByTagName('h1')[0].firstChild.nodeValue = this.featureStack[this.Index].feature.head;
            $(this.target).getElementsByTagName('p')[0].firstChild.nodeValue = this.featureStack[this.Index].feature.summary;
        } else { // in case the db barfed
            this.indicatorStack[0].src = '/images/' + this.indicators + 'Next.gif';
        }
        this.Counter++;
        if (parseFloat(navigator.userAgent.indexOf('6.0')) > 0 && navigator.appName == "Microsoft Internet Explorer" && this.Counter == 5) { this.exit(); }
        else if (this.Counter == 25) { this.exit(); }
    },
    
    displayArbitraryFeature : function(f) {
        //console.log('displayArbitraryFeature');
        this.indicatorStack[this.Index].src = '/images/' + this.indicators + 'Next.gif';
        try { this.indicatorStack[this.Index].blur(); }
        catch(err) { }
        this.Index = f == 0 ? 4 : (f - 1) % 5;
        this.pe.stop();
        this.displayNextFeature();
        this.start();
    },
    
    exit : function() {
        this.indicatorStack[0].src = '/images/' + this.indicators + 'Next.gif';
        this.pe.stop();
    }
});

function swapImages(image, newsrc) {
    image.src = newsrc;
}

function preloadImages() {
    var i = new Image;
    $A(arguments).each(function(s) { i.src = s; });
}

document.observe('dom:loaded', function() {
    // Install event handlers
    $('techForYouAnchor').observe('click', audienceNav.b_show);
    $('techForYou').observe('mouseout', audienceNav.b_unpeek);
    $('techForYou').observe('mouseover', audienceNav.b_peek);
    $('closeAudienceNav').observe('click', audienceNav.b_hide);
    
    $('q').observe('focus', function() { $('q').value = ''; });
    
    // Fire up the feature rotator
    if ($('featuredNews')) {
        var featureRotator = new FeatureRotator('featuredNews', 'featureIndicators', 'generateFeature.php', 10);

        $A($('featureIndicators').getElementsByTagName('a')).each(
            function(s) {
                Event.observe(s, 'click', function(e) {
                        featureRotator.displayArbitraryFeature(parseInt(s.href.slice(s.href.indexOf('?')).toQueryParams().n));
                        Event.stop(e);
                    });
            }
        );
    }
    
    // Show audience navigation if we're on the homepage, otherwise, prep for toggling. Note that
    // this somewhat awkward method prevents the dropdown from flickering on load.
    if (document.body.id == 'home') {
        $('audienceNav').removeClassName('hide'); 
        var t = setTimeout('audienceNav.hide()', 2000);
    }
    else {
        $('audienceNav').hide();
        $('audienceNav').removeClassName('hide');
    }
});

var audienceNav = new DropDown('audienceNav', 'techForYou', 'techForYouAnchor');
