var GTBase = {
  Version : '1.0'
};

var DropDown = Class.create({
    Version : '0.1',
    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.trigger).observe('mouseover', this.b_peek);
        $(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

    Version : '0.1',
    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 < 7; i++) { this.requestFeature(i); }
   },
    
    requestFeature : function(i) {
        //console.log('requestFeature');
        new Ajax.Request(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) % 7]) {
            this.indicatorStack[this.Index].src = '/images/' + this.indicators + 'Next.gif';
            this.indicatorStack[(parseInt(this.Index) + 1) % 7].src = '/images/' + this.indicators + 'Progress.gif';
        
            this.Index++;
            this.Index = this.Index % 7;

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

            imageTarget.parentNode.href = this.featureStack[this.Index].feature.link;
            imageTarget.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 ? 6 : (f - 1) % 7;
        this.pe.stop();
        this.displayNextFeature();
        this.start();
    },
    
    exit : function() {
        this.indicatorStack[0].src = '/images/' + this.indicators + 'Next.gif';
        this.pe.stop();
    }
});

var UpdateStamper = Class.create({
    Version : '0.2',
    initialize : function(generator) {
        //console.log('initialize');
        this.generator = generator;
        this.updates;
        this.getAllUpdates();
    },
    getAllUpdates : function() {
        //console.log('getAllUpdates');
        new Ajax.Request(this.generator,
            {
                method:'get',
                onSuccess: function(transport) {
                    var response = transport.responseText || "no response text";
                    if (response.isJSON()) {
                        this.updates = response.evalJSON();
                        this.insertStamps();
                    }                        
                }.bind(this)
            }
        );
    },
    insertStamps : function() {
        //console.log('insertStamps');
        $A(this.updates).each( function(u) {
            a = $(u.element).getElementsByTagName('a')[0];
            a.innerHTML = '<span class="updated" title="' + u.posted + '" style="left: ' + u.left + 'px; top: ' + 
                u.top + 'px; filter: alpha(opacity=' + u.opacityIE + '); -moz-opacity: ' + 
                u.opacity + '; opacity: ' + u.opacity + ';"></span>' + a.innerHTML;
        });
    }
});

var Bubbler = Class.create({
    // TODO: NEEDS ONMOUSEENTER AND ONMOUSELEAVE EVENTS TO FUNCTION PROPERLY
    Version : '0.1',
    inflate : function(e) {
        //console.log('inflate');
        e.element().up().addClassName('top');
        e.element().insert('<span id="audienceNavDetail"></span>', { position: top });
        var detail = e.element().firstDescendant();
        detail.observe('mouseover', function() { return false; });
        new Effect.Scale(detail, 194.11, { duration: 0.3, transition: Effect.Transitions.spring });
        new Effect.Move(detail, { x: -14, y: -8, mode: 'relative', duration: 0.3, transition: Effect.Transitions.spring });
    },
    deflate : function(e) {
        //console.log('deflate');
        var target = (e.element().tagName == 'SPAN') ? e.element().up() : e.element();
        target.up().removeClassName('top');
        target.getElementsByTagName('span')[0].remove();
    }
});

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

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

// TODO: popup stuff should be encapsulated in an object

function isUndefined(v) {
    var undef;
    return v===undef;
}

var _POPUP_FEATURES = 'location=0, statusbar=1, menubar=1, scrollbars=1, width=400, height=475';

function raw_popup(url, target, features) {
    if (isUndefined(features)) {
        features = _POPUP_FEATURES;
    }
    if (isUndefined(target)) {
        target = '_blank';
    }
    var theWindow = window.open(url, target, features);
    theWindow.focus();
    return theWindow;
}

function popup(src, features) {
    return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', features);
}

// functions and classes end here. everything below this line gets executed when this document is loaded.

if (!window.console || !console.firebug) { // prevent errors from debugging debris
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) { window.console[names[i]] = function() {}; }
}

document.observe('dom:loaded', function() {
    // Clear search field when focused
    if ($('q')) {
        $('q').observe('focus', function() {
                if ($('q').value == 'Search') { $('q').value = ''; }
            });
    }
    
    // Fire up the feature rotator, if necessary.
    if ($('featureRotator')) {
        var featureRotator = new FeatureRotator('featureRotator', 'featureIndicators', '/inc/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);
                    });
            }
        );
    }

    // Dole out updated stamps if need be.
    if ($('departments')) {
        //var updateStamper = new UpdateStamper('/inc/generateUpdateStamps.php');
    }
    
    // Show audience navigation if we're on the homepage.
    if (document.body.id == 'home') {
        $('audienceNav').removeClassName('hide');
        $('closeAudienceNav').observe('click', audienceNav.b_hide);
//        var an = $A($('audienceNav').getElementsByTagName('a'));
//        an.pop();
//        an.each(function(s) { Event.observe(s, 'mouseover', bubbler.inflate); });
//        an.each(function(s) { Event.observe(s, 'mouseout', bubbler.deflate); });
    } else {
        if ($('audienceNav')) {
            $('audienceNav').hide();
            $('audienceNav').removeClassName('hide');
            $('techForYouAnchor').observe('click', audienceNav.b_show);
            $('techForYou').observe('mouseout', audienceNav.b_unpeek);
            $('techForYou').observe('mouseover', audienceNav.b_peek);
            $('closeAudienceNav').observe('click', audienceNav.b_hide);
        }
    }
});

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

