var Homepage = Class.create({
	initialize: function(options) {
	    var options = options || {};	
	    
        this.options = $H({
            // Constants
            SIDESCROLLER_FRAME_ID: 'sidescroller_frame',
            SIDESCROLLER_CONTROLS_ID: 'group_controls',
            
            // Variables
		    scrollerOptions: {},
		    pagingOptions: {}
		    
        }).merge(options).toObject();
        
        this.instantiateScroller();
		(this.scroller.slides.length > 1) ? this.isSinglePage = false : this.isSinglePage = true;
		
        this.registerEventHandlers();
		this.animateIn();

		var trigger = $$('#group_controls li.group').first();
		this.triggerWidth = parseInt(trigger.getStyle('margin-right')) + parseInt(trigger.getStyle('width'));
		this.modifier = 5; // Starting offset of the indicator in px
		
		var left = this.modifier + (this.lastSlideIndex * this.triggerWidth);
		
		$$('#group_controls ul').first().setStyle({
			backgroundPosition: left+'px 0px'
		});
		if (this.isSinglePage){
			$(this.options.SIDESCROLLER_CONTROLS_ID).hide();	
			$("scroller_controls_wrapper").hide();
			$("sidescroller_glow_left").hide();
			$("sidescroller_glow_right").hide();
		}
	},

    instantiateScroller: function() {

        var scrollerFrame = $(this.options.SIDESCROLLER_FRAME_ID);
        var scrollerOptions = $H({
			'durationPerSlide': 0.5, 
			'restAlignment': 'left'						
		}).merge(this.options.scrollerOptions).toObject();
		
		var scrollerControls = $(this.options.SIDESCROLLER_CONTROLS_ID); // the paging control container
		
		this.lastSlideIndex = $$("ul.slidelist > li").length -1;
		
		var pagingOptions = $H({
			'itemsPerGroup': 1, 
			'initialGroupIndex': this.lastSlideIndex,
			'previousGroupTriggerID': 'previous_group',
			'nextGroupTriggerID': 'next_group',				
			'autoGenerate': true		
		}).merge(this.options.pagingOptions).toObject();
		
        // instantiate scroller
		this.scroller = new ScrollerPagingControl(scrollerFrame, scrollerOptions, scrollerControls, pagingOptions); 
    },
    
    registerEventHandlers: function() {
        $(this.options.SIDESCROLLER_FRAME_ID).observe('scroller:slideselected', this.updateIndicatorPosition.bindAsEventListener(this));    
    },
    
	updateIndicatorPosition: function(e) {		
		var left = this.modifier + (e.memo.slideIndex * this.triggerWidth);
		$$('#group_controls ul').first().morph('background-position: '+left+'px 0px;', {
			duration: 0.2
		});
	},
	animateIn: function(){
		var timeout = setTimeout(function(){
			this.scroller.moveToFirstGroup();
		}.bind(this), 500)
	}
});  				    

Element.addMethods({
	fadeSprite: function(element, options) {
		var element = $(element);
		return new SpriteAnimatorController(element, options);
	}
});

var SpriteAnimator = Class.create({
	initialize: function(element, options){
		this.options = Object.extend({
			duration: 0.5,
			transition: Effect.Transitions.sinoidal,
			mode: "absolute"
		}, options || {});
		this.spriteEl = element;
		this.spriteEl._originalBgPos = this.spriteEl.getStyle("background-position");
		
		this.spriteChildren = this.spriteEl.descendants();
		this.currentAnimation = null;
		
		// if mode is relative, calculate new bg position
		if(this.options.mode == "relative"){
			this.calculateRelativeBGPosition();
		};
		
		// add necessary css		
		this.addRelativePosition(this.spriteEl);
		this.spriteChildren.map(this.addRelativePosition);
	},
	calculateRelativeBGPosition: function(){
		// get current bg position
		var currentBgArray = this.spriteEl.getStyle("background-position").match(/[-]?\d+/g);
		var currentBgX = parseInt(currentBgArray[0]);
		var currentBgY = parseInt(currentBgArray[1]);
		
		// get new bg position
		var newBgArray = (this.options.bgX+" "+this.options.bgY).match(/[-]?\d+/g);
		var newBgX = parseInt(newBgArray[0]);
		var newBgY = parseInt(newBgArray[1]);
		
		// add them together
		this.options.bgX = (currentBgX + newBgX) + "px";
		this.options.bgY = (currentBgY + newBgY) + "px";
	},
	addRelativePosition: function(element){
		// if the element is not already positioned absolute or relative, set it relative
		var currentPos = element.getStyle("position")	
		if(currentPos == "static"){
			element.setStyle({
				position: "relative",
				zIndex: "1"
			});
		}
	},
	insertDummyElement: function(){
		// add dummy element css
		this.dummyEl = new Element("div", {className: "dummy"}).setStyle({
			position: "absolute",
			top: "0px",
			left: "0px",
			zIndex: "0",
			opacity: 0,
			height: this.spriteEl.getHeight()+"px",
			width: this.spriteEl.getWidth()+"px",
			backgroundImage: this.spriteEl.getStyle("background-image"),
			backgroundPosition: this.options.bgX+" "+this.options.bgY
		});
		
		// insert dummy element
		this.spriteEl.insert({top: this.dummyEl});
		
		// fade in dummy element
		this.fadeInDummyElement();
	},
	fadeInDummyElement: function(){
		this.currentAnimation = new Effect.Fade(this.dummyEl, {
			duration: this.options.duration,
			from: this.dummyEl.getStyle("opacity") || 0, 
			to: 1,
			transition: Effect.Transitions.sinoidal,
			afterFinish: function(){
				this.currentAnimation = null;
			}.bind(this)
		});
	},
	fadeOutDummyElement: function(){
		this.currentAnimation = new Effect.Fade(this.dummyEl, {
			duration: 0.5,
			from: this.dummyEl.getStyle("opacity") || 1, 
			to: 0,
			transition: Effect.Transitions.sinoidal,
			afterFinish: function(){
				this.currentAnimation = null;
				this.removeDummyElement();
			}.bind(this)
		});		
	},
	removeDummyElement: function(){
		this.dummyEl.remove();
		// remove all other dummy elements if they exist
		this.spriteEl.select(".dummy").invoke("remove");
	},
	pauseAnimation: function(){
		if(this.currentAnimation){
			this.currentAnimation.cancel();
		}
	}
});

var SpriteAnimatorController = Class.create(SpriteAnimator,{
	initialize: function($super, element, options){
		// call super class's initialize
		$super(element, options);
		
		this.spriteParent = this.spriteEl.up();
		
		// attach event listeners to mouseover and moueout
		this.spriteParent.observe("mouseenter", this.__mouseOver.bindAsEventListener(this));
		this.spriteParent.observe("mouseleave", this.__mouseOut.bindAsEventListener(this));	
	},
	__mouseOver: function(e){
		this.spriteEl.setStyle({
			backgroundPosition: this.spriteEl._originalBgPos
		});
		this.pauseAnimation();
		this.insertDummyElement();
	},
	__mouseOut: function(e){	
		// firefox right-click menu fires mouseout with a related target of null
		this.pauseAnimation();
		this.fadeOutDummyElement();
	}
});


// Some IE Specific Fixes

// fixes prototype's Element.getStyle to properly get background-position in IE
if (Prototype.Browser.IE) {
	Element.addMethods({
		getStyle: Element.Methods.getStyle.wrap(
			function(proceed, element, style){			
				if(style == "backgroundPosition" || style == "background-position"){
					element = $(element);
					style = style.camelize();
					var value = element.style[style];
					if (!value && element.currentStyle){ 
						value = element.currentStyle[style+"X"]+" "+element.currentStyle[style+"Y"];
					}
					return value == '0% 0%' ? null : value;
				} else {
					return proceed(element, style);
				}
			}	
		)
	});
}

// Instantiation
document.observe("dom:loaded", function () {
	$$("div.homepage div#masthead ul.slidelist ul li a div.icon").invoke("fadeSprite", {
		bgY: "0px",
		bgX: "-68px",
		mode: "relative"
	});

	new Homepage();

	// Initialize homepage banner crossfader
	new CrossFadeControls({
		'duration': 1,
		'timerDuration': 7000,
		'elEventHandler': $('homepage_banner_rotator'),
		'viewport': $('homepage_banner_rotator'),
		'pagination': false,
		'navigation': false,
		callback: function(){
			var slideTitle = $$('div.homepage li.current')[0].getAttribute('data-title');

            // Removed per Ben Brooks.  Issue view item 0171.
			//_gaq.push(['_trackEvent', 'Hero Image', 'Pageview', slideTitle]);
		}
	});

	// Show homepage banner rotator
	$('homepage_banner_rotator').setStyle({
		'visibility': 'visible',
		'opacity': 0
	}).appear();

	// Show the first panel
	$$('#homepage_banner_rotator li.homepage_banner').invoke('hide').first().show();

});			



