var quickNav = new Class({
    initialize: function(containerID){
		this.navBox = $(containerID);
		if(!this.navBox) {
			return;	
		}		
		this.trigger = this.navBox.getElement('.starter');
		this.menu = this.navBox.getElement('.secondary');
		this.menuEffect = new Fx.Slide(this.menu, {
			duration: 300,
			transition: Fx.Transitions.Cubic.easeIn
		});

		this.menuEffect.hide();
		this.menu.style.visibility = "visible";

		this.trigger.addEvent("click", function(e) {
			e = new Event(e);													
			this.menuEffect.toggle();
			e.stop();
		}.bind(this));

	}
});

function personaRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var personaLink = $('gusChangePersona').get('href');
	if (personaLink.indexOf('?') > -1) {
		if (personaLink.indexOf('&') > -1) {
			personaLink = personaLink + "&";
		}
	} else {
		personaLink = personaLink + "?";
	}
	this.document.location = personaLink + "surl=" + returnTo; 
} 
function logoutRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var logoutLink = $('gus_logout_link').get('href');
	if (logoutLink.indexOf('?') > -1) {
		if (logoutLink.indexOf('&') > -1) {
			logoutLink = logoutLink + "&";
		}
	} else {
		logoutLink = logoutLink + "?";
	}
	this.document.location = logoutLink + "&surl=" + returnTo; 
} 
function loginRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var loginLink = $('gus_login_link').get('href');
	this.document.location = loginLink + "&surl=" + returnTo; 
} 
function registerRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var regLink = $('gus_register_link').get('href');
	this.document.location = regLink + "&surl=" + returnTo; 
}

window.addEvent('domready', function() {
	var gusNavEAMenu = new quickNav('gus_ea');
	if (loggedinMenuActive) var gusNavWelcomeMenu = new quickNav('gus_welcome');
});

var FilmStrip = new Class({
    initialize: function(myOptions){
		this.myOptions = myOptions;
		this.container = $(this.myOptions.id);

		// get elements and their size
		this.getElements();
		// init paging
		this.initPaging();
		
		// set film strips height or width
		if(this.myOptions.scrollDir == 'vertical'){
			this.filmStrip.setStyle("height", this.pages*this.viewPortHeight+"px");
		} else {
			this.filmStrip.setStyle('left', '0');
			this.filmStrip.setStyle("width", this.pages*(this.viewPortWidth + this.offset) +"px");
		}
		
		//create effect
		($type(this.myOptions.transitionSpeed)) ? this.transitionSpeed = this.myOptions.transitionSpeed : this.transitionSpeed = 200;		
		($type(this.myOptions.transitionType)) ? this.transitionType = this.myOptions.transitionType : this.transitionType = Fx.Transitions.Sine.easeInOut;
		this.setupEffect();
		
		// show or hide the pagination controls
		this.setPaginationControls();

		// attach all the click handlers to the next and previous buttons
		this.nextButton.removeEvents();
		this.nextButton.addEvent('click', function(e) {	
			e = new Event(e);
			this.setPage(1);
			e.stop(); 
		}.bind(this));
		this.prevButton.removeEvents();
		this.prevButton.addEvent('click', function(e) {
			e = new Event(e);
			this.setPage(-1);
			e.stop();
			}.bind(this));	
	},
	setupEffect: function() {
		this.pageSlider = new Fx.Tween(this.filmStrip, {
			duration: this.transitionSpeed,
			transition: this.transitionType
		});		
	},
	getElements: function() {
		this.viewPort = this.container.getElement(this.myOptions.viewPort);	
    	this.filmStrip = this.viewPort.getElement(this.myOptions.filmStrip);
    	this.prevButton = this.container.getElement(this.myOptions.prevButton);
    	this.nextButton = this.container.getElement(this.myOptions.nextButton);
    	(this.myOptions.offset) ? this.offset = Number(this.myOptions.offset) : this.offset = 0;
    	(this.myOptions.caption) ? this.caption = this.container.getElement(this.myOptions.caption) : this.caption = false;
    	this.activityLabels = this.filmStrip.getElements('a');
		this.getElementSize();
	},
	getElementSize: function() {
		($type(this.myOptions.viewPortWidth)) ? this.viewPortWidth = Number(this.myOptions.viewPortWidth) : this.viewPortWidth = this.viewPort.getSize().x;
		($type(this.myOptions.viewPortHeight)) ? this.viewPortHeight = Number(this.myOptions.viewPortHeight) : this.viewPortHeight = this.viewPort.getSize().y;
		($type(this.myOptions.filmStripHeight)) ? this.filmStripHeight = Number(this.myOptions.filmStripHeight) : this.filmStripHeight = this.filmStrip.getSize().y;
	},
	initPaging: function() {
		this.curPage = 0;
		if(this.myOptions.scrollDir == 'vertical'){
			this.pages = Math.ceil(this.filmStripHeight/this.viewPortHeight);
		} else {
			this.itemPerPage = this.myOptions.itemPerPage;			
			this.numResults = + this.activityLabels.length;
			this.pages = Math.ceil(this.numResults/this.itemPerPage);	
		}	
	},
	goToItem: function(item) {
		var targetPage = (Math.ceil((item + 1)/this.myOptions.itemPerPage)) -1;
		var diff = targetPage-this.curPage;
		if (diff != 0) this.setPage(diff)
	},
	setPage: function(direction) {
		
		// Update curpage
		this.curPage = this.curPage + direction;
		
		// determine the pages new left value
		var filmstripScrollPosition;
		if(this.myOptions.scrollDir == 'vertical'){
			 filmstripScrollPosition = this.viewPortHeight * -(this.curPage);
		} else {
			filmstripScrollPosition = (this.viewPortWidth + this.offset) * -(this.curPage);
		}

		(this.myOptions.scrollDir == 'vertical') ? this.styleType = 'top' : this.styleType = 'left';
		this.pageSlider.start(this.styleType , filmstripScrollPosition);
		
		// set the pagination controls
		this.setPaginationControls();
	},
	
	setPaginationControls: function() {
		// decide whether to show or hide each pagination control
		(this.curPage == 0) ? this.prevButton.setStyle("visibility", "hidden") : this.prevButton.setStyle("visibility", "visible");
		// this can be changed to swap a classname if button is still needed but should be greyed out
		(this.curPage == (this.pages-1) || this.numResults == 0) ? 	this.nextButton.setStyle("visibility", "hidden") : this.nextButton.setStyle("visibility", "visible");
		
		if (this.caption) {
			var myFXin = new Fx.Morph(this.caption, {duration:150,  transition: Fx.Transitions.Quad.easeOut});
			var myFXout = new Fx.Morph(this.caption, {duration:150,  transition: Fx.Transitions.Quad.easeIn});
			
			myFXin.start({
				opacity: "0"
				}).chain(function(){	 
				this.caption.innerHTML = this.activityLabels[this.curPage].innerHTML;
				myFXout.start({
					opacity: "1"
				});
			}.bind(this));
		
		}
		
		if($type(this.myOptions.pageCurrent)){
			this.container.getElement(this.myOptions.pageCurrent).innerHTML = this.curPage + 1;
		}
		if(this.myOptions.pageTotal) {
			this.container.getElement(this.myOptions.pageTotal).innerHTML = this.pages;	
		}
	}	
});

/*
Script: FilmStrip.js
	An mootools extension which allows you to easily create a slideshow

License:
	MIT-style license.
*/
var Slideshow = new Class({
	Implements: [Options],				   
	options: {
		hasFade: true,
		loop: true,
		showNav: false,
		frameDelay: 4000,
		items: 'li',
		height: 400,
		width: 400,
		duration: 'normal',
		version: '1.2.03',
		isTrans: false
	},
	initialize: function(containerId, options) {
		
		this.container = $(containerId);
		this.setOptions(options);
		
		// set containers styles
		this.container.setStyles({
			position: 'absolute',
			overflow: 'hidden',
			height: this.options.height,
			width: this.options.width			
		});

		// initialize elements
		this.myElements = this.container.getElements(this.options.items);
		
		// if there is more than 1 elm start slide show, else just show the 1 elm
		if(this.myElements.length > 1 ){
			this.currentIndex = 0;
			this.zIndex = this.myElements.length;
			
			// initialize elements
			this.initElements();			
			this.myElements[this.currentIndex].setStyle('visibility', 'visible');
			
			// start timer
			this.myTimer = this.goTo.delay(this.options.frameDelay, this, this.myElements[this.currentIndex]);
			
		}
	},
	initElements: function(){
		var tmpZ = this.zIndex;
		// initialzie all the items in slide who
		this.myElements.each(function(myElement){
			myElement.setStyles({
				zIndex: tmpZ,
				visibility: 'hidden',
				position: 'absolute',
				top: 0,
				left: 0,				
				height: this.options.height,
				width: this.options.width					
			});	
			tmpZ--;	
		}.bind(this));			
	},
	goTo: function(curElement) {
		// reset for loop only if slideshow items are transparent
		if (this.options.isTrans == true) {	
			this.myElements.each(function(item, index){
				item.setStyle('opacity',0);
			}.bind(this));
		}
		(this.currentIndex == (this.myElements.length-1) && this.options.loop) ? this.currentIndex = 0 : this.currentIndex++;		
		this.zIndex++;	
	
		var nextElement = this.myElements[this.currentIndex];
		// if there is no next element then the user doesnt want to loop the elms
		if($type(nextElement)){
			// set next elms z-index
			nextElement.setStyle('z-index', this.zIndex);
			
			// if its a fading slideshow, else no fade
			if(this.options.hasFade){
				
				// prepage next elm for a fade in
				nextElement.setStyle('opacity', 0);
				// fade in next elm
				new Fx.Tween(nextElement, {
					transition: Fx.Transitions.Sine.easeOut,
					duration: this.options.duration,
					onStart: function(){
						// for extending this class, call a function onTransStart in child class
						if(this.options.showNav && $type(this.onTransStart) == 'function'){
							this.onTransStart();
						}
					}.bind(this),				
					onComplete: function() {
						
						// recusivly call goTo when fade is complete
						this.myTimer = this.goTo.delay(this.options.frameDelay, this, nextElement);	
					}.bind(this)
				}).start('opacity', 0, 1);		
			} else {	
				// no fade so just show elm
				this.myElements[this.currentIndex].setStyle('visibility', 'visible');
				// for extending this class, call a function onTransStart in child class
				if(this.options.showNav && $type(this.onTransStart) == 'function'){
					this.onTransStart();
				}
				// recusivly call goTo
				this.myTimer = this.goTo.delay(this.options.frameDelay, this, nextElement);
			}
		}
	}
});

// toglle module on/off
ToggleModule = new Class({
	Implements: [Options],
	options: {
		
	},
	initialize: function(container, options) {
		this.headers = container.getElements('h3');
		this.headers.each(function(item, index){
			this.toggleMe(item);
		}.bind(this));
	},
	toggleMe: function(header) {
		header.addEvent('click', function(e) {
			header.toggleClass('off');
			$(header.id+'_content').toggleClass('off');
		}.bind(this));	
	}
});

//load component class
var loadComponent = new Class({
    initialize: function(targetDiv, hrefs, autoLoad){
    	this.links = hrefs;
		this.targetDiv = targetDiv;
		this.getUrl(this.links,autoLoad);
    },
    getUrl: function(urls,autoLoad) {
    	//load ajax automatically instead of requiring click on element 
    	if (autoLoad) {
    	  	urls.each(function(item,index){
    			this.loadAjax(item.href);
    	  	}.bind(this)); 		
    	} else {
	    	// attempt to fix silly IE bug. Not sure why IE thinks the href property of an anchor tag is the src of an image.
	    	urls.each(function(item,index){
				item.addEvent('click',function(event){
					this.loadAjax(item.href);
					event.stop();
				}.bind(this));
			}.bind(this));
    	}
    },
	loadAjax: function(myUrl) {
		var myRequest = new Request.HTML({
			url: myUrl,
			method: 'get',
			evalScripts: false,
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				this.targetDiv.removeClass('preloader');
				this.targetDiv.set('html',responseHTML);
				eval(responseJavaScript);
			}.bind(this),
			onRequest: function() {
				this.targetDiv.empty();
				this.targetDiv.addClass('preloader');
			}.bind(this),
			onFailure: function() {
				this.targetDiv.removeClass('preloader');
				this.targetDiv.set('html','<p class="error">Error loading component.</p>');
			}.bind(this)
		}).send();
	}
});

// subnav
HoverMenu = new Class({
	Implements: [Options],
	options: {},
	initialize: function(source, options) {
		this.setOptions(options);
		this.source = $(source);
		this.subNav = this.source.getElement(".subNav");
		this.button = this.source.getElement(".btn");
		if (!this.source.hasClass("hoverMenu")) {
			this.source.addEvent('mouseenter', (function() {
				$$(".subNav").each(function(el) { el.setStyle('display', 'none');; });
				//this.subNav.setStyles({visibility: 'hidden', display: ''});
				this.source.addClass("hoverMenu");
				this.subNav.setStyles({
					//left: 0,
					//visibility: 'visible'
					display:'block'
				});
			}).bind(this));
			this.source.addEvent('mouseleave', (function() {
				this.source.removeClass("hoverMenu");
				$$(".subNav").each(function(el) { el.setStyle('display', ''); });
			}).bind(this));
		}
	}
});

//legal confirm for external links
function confirmExtLegal(){
	var acceptsTerms = "You are about to leave the Electronic Arts website and go to a website owned by a third party.  Electronic Arts is not responsible for content on third party sites, and our privacy policy does not apply to their information collection practices.  Press OK to access the linked site or press CANCEL to return to your original page.";
	return confirm(acceptsTerms);	
}

//legal confirm for download links
function confirmLegal(){
	var acceptsTerms = "Terms & Conditions of Downloading Materials\n\nThe materials provided on this web site are provided \"as is\" without warranties of any kind.  Electronic Arts Inc., its subsidiaries, divisions, affiliates and licensors (\"EA\") disclaim all warranties, either express of implied, including but not limited to, warranties of merchantability and fitness for a particular purpose. To the extent allowed by applicable law, in no event will EA be liable for damages of any kind to your hardware, peripherals or software programs as a result of your download or use of our materials.\n\n You may download one copy of the materials onto a single computer for your personal, non-commercial, home use only, provided you keep intact all copyright, trademark and other proprietary notices.  No materials from this web site may be copied, reproduced, modified, republished, uploaded, posted, transmitted, broadcast or distributed in any way without the express written consent of EA.  Unauthorized use of the materials is a violation of EA's copyright and constitutes infringement of EA's proprietary rights.\n\nTo use these materials, you must agree to the above terms and conditions.  To accept this agreement and proceed with the download, click \"OK\" or click \"Cancel\" to decline.";	
	return confirm(acceptsTerms);
}

function openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName) {
	openPopup(url, name, width, height, status, scrollbars, moreProperties);
}

function openCenteredWindow(url, name, width, height){
    openPopup(url, name, width, height,'yes');
}

// GLOBAL WINDOW POPUP (Used everywhere there's a popup.)
function openPopup(url, name, width, height, status, scrollbars, moreProperties) {
	var agent = navigator.userAgent.toLowerCase();
	var x, y = 0;
	if (screen) {
      x = (screen.availWidth - width) / 2;
      y = (screen.availHeight - height) / 2;
   }
   if (!status) status = '';

	// Adjust width if scrollbars are used (pc places scrollbars inside the content area; mac outside) 
	width += (scrollbars != '' && scrollbars != null && agent.indexOf("mac") == -1) ? 16 : 0;

	var properties = 'width=' + width + ',height=' + height + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y + ((status) ? ',status' : '') + ',scrollbars' + ((scrollbars) ? '' : '=no') + ((moreProperties) ? ',' + moreProperties : '');
   
	window.open(url, name, properties);
	return false;
}
// generic hover class
function ieHover(context){
	if(!context){return}
	
	$$(context).each(function(hoverItem) {
		hoverItem.addEvent("mouseover", function(event) {
			hoverItem.addClass("hover");	
		}.bind(this));
		hoverItem.addEvent("mouseout", function(event) {
			hoverItem.removeClass("hover");	
		}.bind(this));
	}.bind(this));
}

/*****************************************/
/* GENERIC POPUP OVERLAY */

var Overlay = new Class({
    initialize: function(containerID,trigger,popupHeight,autoOpen,toTop){
    	this.myContainer 	= $(containerID);
    	this.toTop		 	= toTop;
    	this.myFade 		= this.myContainer.getElement('.fade');
    	this.myPopup 		= this.myContainer.getElement('.popup');
    	this.myWrapper 		= this.myContainer.getElement('.wrapper');
    	if (this.myContainer.getElements('.close')) {
    		this.closeButtons = this.myContainer.getElements('.close');
    		this.closeButtons.each(function(item){
    			item.addEvent('click', function(e) {
	    			this.closeOverlay();
	    			e.stop();
	    		}.bind(this));
    		}.bind(this));
    	};

    	if (trigger) {
	    	this.myTriggers		= document.getElements(trigger);
	    	this.myTriggers.each(function(item){
	    		item.addEvent('click', function(e) {
	    			this.showOverlay();
	    			e.stop();
	    		}.bind(this));
	    	}.bind(this));
    	}
    	
    	this.myPopupHeight	= popupHeight +"px";

    	
    	if (autoOpen) this.showOverlay();
    
    },
    showOverlay: function(){

		//I6 FIX
		if ((Browser.Engine.trident) && (Browser.Engine.version <= 4)) {
			var topPos = document.documentElement.scrollTop + 274;
			var fadeWidth = document.documentElement.clientWidth;
			this.myPopup.setStyle('position','absolute');
			this.myPopup.setStyle('top',topPos + 'px');
			this.myFade.setStyle('width',fadeWidth + 'px');
			this.myPopup.setStyle('left',fadeWidth / 2 + 'px');
		}
		
		if(this.toTop) {
			//scroll to top (fixes several IE bugs)
			var myScroll = new Fx.Scroll(window).toTop(this);
		}
		
		
		this.myFade.setStyle('opacity','0');
		this.myPopup.setStyle('height','0px');
		this.myWrapper.setStyle('opacity','0');
		this.myContainer.setStyle('display','block');
		
		var myFx1 = new Fx.Tween(this.myFade,{duration:500});
		var myFx2 = new Fx.Tween(this.myPopup, {duration:500});
		var myFx3 = new Fx.Tween(this.myWrapper, {duration:500});
		
		myFx1.start('opacity','.8').chain(function(){
			myFx2.start('height',this.myPopupHeight).chain(function(){
				myFx3.start('opacity','1');
			});
		}.bind(this));
		
    },
    closeOverlay: function(){
		this.myContainer.setStyle('display','none');
    }
});

/*****************************************/
/* SHARING WIDGET */

var Sharing = new Class({
	initialize: function(containerID,trigger,overlayRef){
		
		this.myContainer 	= $(containerID);
		this.myTarget 		= this.myContainer.getElement('.sites');
		this.myTextarea 	= this.myContainer.getElement('textarea');
		this.overlayRef 	= overlayRef;
		
		this.myTextarea.addEvent('click', function(e) {
			this.focus();
			this.select();
		});
		
		
		this.mySites 		= new Array();
		
		this.mySites[0] = new Array(
			'facebook',
			'send to Facebook',
			'http://www.facebook.com/sharer.php?u=[URL]&t=[TITLE]'
			);
		
		this.mySites[1] = new Array(
			'delicious',
			'send to del.icio.us',
			'http://del.icio.us/post?url=[URL]&title=[TITLE]'
			);

		this.mySites[2] = new Array(
			'digg',
			'send to digg',
			'http://digg.com/submit?phase=2&url=[URL]&title=[TITLE]'
			);
		
/*		this.mySites[3] = new Array(
			'stumbleupon',
			'send to stumbleupon',
			'http://www.stumbleupon.com/refer.php?url=[URL]&title=[TITLE]'
			);
		
		this.mySites[4] = new Array(
			'twitter',
			'send to twitter',
			'http://twitter.com/timeline/home?status=[URL]'
			);		
*/		
		if (trigger) {
	    	this.myTriggers	= document.getElements(trigger);
	    	this.myTriggers.each(function(item){
	    		item.addEvent('click', function(e) {	
		    		if (item.title) {
		    			this.title = item.title;
		    		} else {
		    			this.title = document.title;
		    		}
		    		if (item.href) {
		    			this.url = item.href;
		    		} else {
		    			this.url = window.location;
		    		}
	    			this.buildLinks();
	    			e.stop();
	    		}.bind(this));
	    	}.bind(this));
    	}
		
	},
	buildLinks: function() {
		this.myTextarea.empty();
		this.myTextarea.setProperty('html',this.url);
		this.myTarget.empty();
		this.mySites.each(function(item){
			var link = item[2].replace("[URL]",encodeURIComponent(this.url)).replace("[TITLE]",encodeURI(this.title));
			var a = new Element('a',{
				'class': item[0],
				'title': item[1],
				'href': link
		   	});
			a.inject(this.myTarget);
			a.addEvent('click', function(e) {
				e.stop();
				return confirmExtLegal(link); 
				if(this.overlayRef) this.overlayRef.closeOverlay();
			}.bind(this)); 
		}.bind(this)); 
	}
});

var Dropdown = new Class({
	initialize: function(container) {
		var trigger 	= container.getElement('.trigger');
		var links 		= container.getElements('.filter a');
		var caption 	= container.getElement('.caption span');
		
		container.addEvent('mouseleave', function(e) {
			container.removeClass('on');
		});
		
		trigger.addEvent('click', function(e) {
			e.stop();
			container.addClass('on');
		});
				
		links.each(function(item, index){
			item.addEvent('click', function(e) {
				e.stop();
				window.location = item;
				container.removeClass('on');
			});
		});
	}	
});

window.addEvent('domready', function() {
	$$("#header #navBar .hasSubnav .subNav").each(function(btn) { new HoverMenu(btn.parentNode); });
	// set gus register link to proper sports URL
	if($('gus_register')) {
		var curReg = $('gus_register').getElement('a');
		var curDomain = curReg.href.split('?')[0];
		curReg.href = curDomain+'?registrationSource=NHL-NHL10&locale=en_US&ref=EASports';
	}
	// set gus login link to proper sports URL
	if($('gus_login')) {
		var curLogin = $('gus_login').getElement('a');
		var curDomain = curLogin.href.split('?')[0];
		curLogin.href = curDomain+'?selectprofile=true&authenticationSource=NHL-NHL10&locale=en_US&ref=EASports';
	}
	if ($('gus_welcome')) {
		var anchors = $('gus_welcome').getElementsByTagName("a"), 
			url_test = /(\/myinfo.do)|(\/selectprofile.do)/,
			query;
				
		for (var i=0, l=anchors.length; i<l; i++) {
			if (url_test.test(anchors[i].pathname)) {
				query = anchors[i].search + "?";
				query = query.split("?")[1];
             	if (query.length == 0) {
             		query = [];
             	} else {
             		query = query.split("&");
             	}
				query[query.length] = "ref=EASports";
				anchors[i].search = "?" + query.join("&");
			}
		}
	}

});
