if (typeof(Aperture) == 'undefined') Aperture = {};


Aperture.FreeTrialOverlay = Class.create({
    duration: .25,
    handleClassName: 'trialoverlay-handle',
    overlayClassName: 'trialoverlay',
    eventName: 'click',

    initialize: function(button, overlay) {
        this.button = button;
        this.overlay = overlay;
        if (!this.button || !this.overlay) return;
        if (this.button.tagName.toLowerCase() != 'a' && !this.button.down('a')) return;

        this.button.observe(this.eventName, this.toggle.bind(this));

        this._escape = Event.observe(window, 'keyup', function(evt) {
            if (evt.keyCode == Event.KEY_ESC) this.close();
        }.bind(this));
    },

    handleDocClick: function(evt) {
        if (!(evt.findElement('.'+this.handleClassName)) && !(evt.findElement('.'+this.overlayClassName))) {
            this.close();
        }
    },

    toggle: function(evt) {
        evt.stop();

        if (!this.overlay.visible()) {
            this.open();
        } else {
            this.close(this.overlay);
        }
    },

    open: function() {
        this.close();

        this.button.addClassName('active');

        if (!this.overlay.visible()) {
            this.overlay.appear({
                duration: this.duration,
                afterFinish: function() {
                    this.docClick = document.observe(this.eventName, this.handleDocClick.bind(this));
                }.bind(this)
            });
        }

        // tracking
        if (this.overlay.down('iframe').src.match('/cgi-bin/WebObjects/')) {
            AC.Tracking.trackPage({ pageName: 'aperture - trial - overlay (us)' });
        }
    },

    close: function() {
        if (this.docClick) {
            document.stopObserving(this.eventName, this.docClick);
            this.docClick = null;
        }

        Aperture.FreeTrialOverlay.overlays.each(function(overlay) {
            overlay.hide();
        });
    },

    hide: function(overlay) {
        this.button.removeClassName('active');

        if (this.overlay.visible()) {
            this.overlay.fade({ duration: this.duration });
        }
    }
});
Aperture.FreeTrialOverlay.overlays = [];


Aperture.FreeTrialOverlay.overlays.push(new Aperture.FreeTrialOverlay($('pn-freetrial'), $('trialoverlay')));
