/**
 **********************************************************************************
 *  Global calls
 **********************************************************************************
 */
(function()
{
    /**
     *  Fix IE background image flicker
     *  http://www.mister-pixel.com/
     */
    try
    {
	    document.execCommand('BackgroundImageCache', false, true);
    }
    catch(e) {}
    
    linkExternal = function(obj, linkName)
    {
        omnitureTag(obj, 'e', linkName);
    };

    linkCustom = function(obj, linkName)
    {
        omnitureTag(obj, 'o', linkName);
    }

    linkDownload = function(obj, linkName)
    {
        omnitureTag(obj, 'd', linkName);
    }
    
    omnitureTag = function(obj, type, linkName)
    {
        var s = s_gi(s_account);
        s.linkTrackVars = 'None';
        s.linkTrackEvents = 'None';
        var lt = (obj.href != null) ? s.lt(obj.href) : "";
        if (lt=="")
        {
            s.tl(obj, type, linkName);
        }
    };
})();

/**
 **********************************************************************************
 *  GoRedWithCampbells namespace
 **********************************************************************************
 */
var GoRedWithCampbells = {
    init: function()
    {
        new GoRedWithCampbells.Navigation();
        new GoRedWithCampbells.Donate();
        new GoRedWithCampbells.Stories();
    }
};

/**
 **********************************************************************************
 *  Navigation
 **********************************************************************************
 */
GoRedWithCampbells.Navigation = Class.create({
    // Constructor
    initialize: function()
    {
        this.container = $('nav-main');
        if (this.container == null) return;
        
        this.buildCache();
        this.attachEvents();
    },
    
    // Private Methods
    buildCache: function()
    {
        this.mainNavItemsWithSubNav = $(this.container).select('li#getinvolvedmenu, li#heartsmartsmenu, li#campbellcommitmentmenu');
    },
    
    attachEvents: function()
    {
        this.mainNavItemsWithSubNav.invoke('observe', 'mouseenter', this.onNavHover.bind(this)).invoke('observe', 'mouseleave', this.onNavHover.bind(this));
    },
    
    onNavHover: function(event)
    {
        var element = event.element();
        var listItem = (element.nodeName == 'LI' && element.select('ul').length > 0) ? element : element.up('li#getinvolvedmenu, li#heartsmartsmenu, li#campbellcommitmentmenu');
        if (event.type == 'mouseover' || event.type == 'mouseenter')
        {
            listItem.select('ul').invoke('setStyle', {display: 'block'});
            this.container.addClassName(listItem.id + '-hover');
            return;
        }
        listItem.select('ul').invoke('setStyle', {display: 'none'});
        this.container.removeClassName(listItem.id + '-hover');
    }
});

/**
 **********************************************************************************
 *  Donate
 **********************************************************************************
 */
GoRedWithCampbells.Donate = Class.create({
    // Constructor
    initialize: function()
    {
        this.container = $('donate');
        if (this.container == null) return;
        
        // set up methods
        this.buildCache();
        this.build();
        this.attachEvents();
    },
    
    // Private Methods
    buildCache: function()
    {
        this.action = new Element('div', {id: 'action'}).update('<a href="javascript:linkCustom(this, \'AYH: Click to Donate\');"><img alt="Click Now" src="images/get-involved/btn-click-to-help.gif" width="398" height="31" /></a>');
        this.thanks = new Element('div', {id: 'thanks'}).update('<h4>Thanks for clicking to donate!</h4> <p>For each click, we&#8217;re donating $1 up to $625,000 to the American Heart Association&#8217;s Go Red For Women&#0174; movement. <a href="TellAFriend.aspx" class="more-info">Tell a Friend &gt;</a></p>').hide();
    },
    
    build: function()
    {
        this.container.insert(this.action);
        this.container.insert(this.thanks);
    },
    
    attachEvents: function()
    {
        this.action.observe('click', this.onDonateClick.bind(this));
    },
    
    onDonateClick: function(event)
    {
        this.action.hide();
        this.thanks.show();
    }
});

/**
 **********************************************************************************
 *  Stories
 **********************************************************************************
 */
GoRedWithCampbells.Stories = Class.create({
    _modalCache: {}, // modal overlay cache
    
    // Constructor
    initialize: function()
    {
        this.links = $$('a.story');
        if (this.links.length == 0) return;
        
        // set up methods
        this.attachEvents();
    },
    
    // Private Methods
    attachEvents: function()
    {
        this.links.invoke('observe', 'click', this.onLinkClick.bind(this));
    },
    
    onLinkClick: function(event)
    {
        Event.stop(event); // stop default click event
        
        var element = Event.element(event); // get event element
        this.storyUrl = element.href;
        this.type = (this.storyUrl.indexOf('stories') == -1) ? 'finalist-story' : 'stories';
        
        this[(this._modalCache[this.storyUrl]) ? 'showModal' : 'getHtml'](); // if data already exists, use cached version (based off URL)
    },
    
    getHtml: function()
    {
        new Ajax.Request(this.storyUrl, {method: 'get', onSuccess: this.buildModal.bind(this), onFailure: this.error.bind(this)});
    },
    
    buildModal: function(response)
    {
        var html = response.responseText;
        this._modalCache[this.storyUrl] = new GoRedWithCampbells.Modal(this.type, html);
        this.showModal();
    },
    
    showModal: function()
    {
        $(document.body).insert(this._modalCache[this.storyUrl]); // insert above footer so print version is in correct order
        document.fire('modal:show');
    },
    
    error: function()
    {
        alert('This feature is currently unavailable.');
    }
});

/**
 **********************************************************************************
 *  Modal Template
 **********************************************************************************
 */
GoRedWithCampbells.Modal = Class.create({
    _topMargin: 24,
    _leftMargin: 20,
    _overlayOpacity: 0.35,
    _duration: 0.5,
    
    // Constructor
    initialize: function(type, data)
    {
        this.type = type;
        this.data = data;
        
        // set up methods
        this.buildCache();
        this.buildOverlay();
        this.attachEvents();
    },
    
    // Public Methods
    toElement: function()
    {
        // attach custom events each time modal is show (removed when hidden)
        document.observe('modal:show', this.bRender);
        this.overlay.observe('click', this.bOnOverlayClick);
        Event.observe(document.onresize ? document : window, 'resize', this.bReset);
        
        return this.container.show();
    },
    
    // Private Methods
    buildCache: function()
    {
        // cached bound function calls
        this.bOnOverlayClick = this.onOverlayClick.bindAsEventListener(this);
        this.bRender = this.render.bind(this);
        this.bReset = this.reset.bind(this);
        
        // cached dimensions
        this.pageDimensions = $('header').getDimensions();
        this.defaultTop = this.pageDimensions.height + this._topMargin;
        
        // cached elements
        this.close = new Element('p', {id: 'close'}).insert(new Element('a', {href: '#close'}).update('CLOSE X'));
        this.container = new Element('div', {id: 'container-modal', className: this.type}).insert(this.close).insert(this.data);
        this.iframeShim = new Element('iframe', {src: 'javascript:false;', id: 'shim', frameBorder: 0}); // only used in IE
    },
    
    buildOverlay: function()
    {
        if ($('overlay')) // check if overlay DOM element already exists
        {
            this.overlay = $('overlay'); // get already existing overlay DOM element
            return;
        }
        
        this.overlay = new Element('div', {id: 'overlay', style: 'display: none'}); // create overlay DOM element
        $(document.body).insert(this.overlay); // insert overlay into DOM
    },
    
    attachEvents: function()
    {
        this.close.observe('click', this.onCloseClick.bindAsEventListener(this));
    },
    
    onCloseClick: function(event)
    {
        Event.stop(event); // stop default click event
        
        this.hide();
    },
    
    onOverlayClick: function(event)
	{
	    this.hide();
	},
    
    render: function()
    {
        // get dimensions
        this.bodyDimensions = $(document.body).getDimensions();
	    this.viewportDimensions = $(document.viewport).getDimensions();
	    this.containerDimensions = this.container.getDimensions();
	    var containerVerticalPosition = this.getVerticalPosition();
        var containerHorizontalPosition = this.getHorizontalPosition();
        
        // stretch overlay to fill page
		this.setOverlaySize(parseInt(containerVerticalPosition.top));
		// animate background overlay
        this.showOverlay();
        
        // set modal window position according to page size/position
        this.container.setStyle(Object.extend(containerHorizontalPosition, containerVerticalPosition));
	    
	    // IE needs iframe shim to cover "bleed-through" elements
        if (Prototype.Browser.IE)
        {
            var defaultStyles = {
                width: this.containerDimensions.width,
                height: this.containerDimensions.height,
                zIndex: this.overlay.getStyle('z-index') - 1
            };
            this.iframeShim.setStyle(Object.extend(defaultStyles, containerVerticalPosition));
            
            $(document.body).insert(this.iframeShim);
        }
    },
    
    reset: function()
    {
        // get dimensions
        this.bodyDimensions = $(document.body).getDimensions();
	    this.viewportDimensions = $(document.viewport).getDimensions();
	    var containerVerticalPosition = this.getVerticalPosition();
        var containerHorizontalPosition = this.getHorizontalPosition();
        
        // restretch overlay to fill page
		this.setOverlaySize(parseInt(containerVerticalPosition.top));
        
        // reset modal window position according to page size/position
        this.container.setStyle(Object.extend(containerHorizontalPosition, containerVerticalPosition));
        
        // reset iframe shim
        if (Prototype.Browser.IE)
        {
            this.iframeShim.setStyle(containerHorizontalPosition);
        }
    },
    
    showOverlay: function()
	{
	    // fade in
		new Effect.Appear(this.overlay, {
		    duration: this._duration,
		    from: 0.0,
		    to: this._overlayOpacity
        });
	},
	
	setOverlaySize: function(containerTopPosition)
    {
        var height = (this.bodyDimensions.height > this.viewportDimensions.height) ? this.bodyDimensions.height : this.viewportDimensions.height;
        
        // need to check height of background overlay since modal window can be longer than the body height
        var bottomOfModalWindow = this.containerDimensions.height + containerTopPosition;
        if (bottomOfModalWindow + this._topMargin > height)
	    {
	        height = bottomOfModalWindow + this._topMargin;
	    }
	    
        this.overlay.setStyle({
            width: (this.viewportDimensions.width < this.pageDimensions.width) ? this.pageDimensions.width + 'px' : '100%',
            height: height + 'px'
        });
    },
	
	hide: function()
    {
        // remove modal window
        this.container.hide().remove();
        
        // remove iframe shim
        if (Prototype.Browser.IE)
        {
            this.iframeShim.remove();
        }
        
        // fade out
        new Effect.Fade(this.overlay, {duration: this._duration});
        
        // dettach events
        document.stopObserving('modal:show', this.bRender);
        this.overlay.stopObserving('click', this.bOnOverlayClick);
        Event.stopObserving(document.onresize ? document : window, 'resize', this.bReset);
    },
    
    getVerticalPosition: function()
    {
        var contentTopOffset = $('content').cumulativeScrollOffset().top;
        
        return {top: ((contentTopOffset > this.defaultTop) ? contentTopOffset + this._topMargin : this.defaultTop) + 'px'};
    },
    
    getHorizontalPosition: function()
    {
        return (this.viewportDimensions.width < this.pageDimensions.width) ? {left: '0', marginLeft: this._leftMargin + 'px'} : {left: '50%', marginLeft: '-428px'};
    }
});

document.observe('dom:loaded', GoRedWithCampbells.init.bind(GoRedWithCampbells));