// tab swapping class
var tabSwap = new Class({
    initialize: function(containerID, context){
		if(!context){
			context = "ul li a";
		}		
		this.tabItems = containerID.getElements(context);
		this.setupTabs();
    },
    setupTabs: function() {
		this.tabItems.each(function(tabItem,index) {
			tabItem.addEvent("click", function(event) {
				this.clearTabs();
				this.setTab(tabItem);
				e.stop();
			}.bind(this));
		}.bind(this));	
	},
    clearTabs: function() {
		this.tabItems.each(function(tabItem,i) {
			if (tabItem.hasClass("selected")) {
				tabItem.removeClass("selected");
			}
		});
    },
	setTab: function(tabItem){
		if (!tabItem.hasClass("selected")) {
			tabItem.addClass("selected");
		}
	}
});

//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();
	}
});

// custom drop down class
var customDD = new Class({
    initialize: function(selectId,isExternalLink){
    	this.container = selectId;
    	this.ddOptions = $$('#'+selectId.id+' ul li a');
    	this.ddTarget = this.container.getElement('ul');
		this.ddTrigger = this.container.getElement('a');
		this.toggleDD(this.ddTrigger,this.ddTarget);
		this.setCategory(this.ddOptions);
		if (!isExternalLink) {
			this.external = false;
		} else {
			this.external = isExternalLink;
		}
    },
    toggleDD: function(trigger,dd){
		trigger.addEvent('click', function(event) {
	    	if (dd.getStyle('display') == 'none') {
	    		dd.setStyle('display','block');
	    	} else {
	    		dd.setStyle('display','none');
	    	}			
			event = new Event(event).stop();
		}.bind(this));
		$(document.body).addEvent('click',function(){
			if(this.ddTarget.getStyle('display') == 'block') {
				this.ddTarget.setStyle('display','none');
			}
		}.bind(this));
    },
    setCategory: function(cats){
    	cats.addEvent('click', function(event) {
	    	var oldTitle = this.container.getElement('span');
	    	oldTitle.set('html',event.target.innerHTML);
	    	this.ddTarget.setStyle('display','none');
			if (this.external == false) {	
				event = new Event(event).stop();
			}
		}.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);	
}
function confirmExtLegal_mx(){
	var acceptsTerms = "Est\341s a punto de abandonar el sitio de Electronic Arts para ir al sitio de un tercero. Electronic Arts no se hace responsable del contenido de terceros, y nuestra pol\355tica de privacidad no aplica a sus pr\341cticas.  Presiona OK para acceder al sitio o presiona CANCEL para regresar a la p\341gina original.";
	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;
} 

var numberSwap = new Class({
	initialize: function(){
			this.allItems = $("numberCard").getElements( "td span" );
			this.setupNumbers();
    },
    setupNumbers: function() {
		this.allItems.each(function(thisItem,index) {
			
			grabHTML = thisItem.get('html');
			
			if( grabHTML == ' ' || grabHTML == ''){ 
				return;
			}
			
			removeWhite = grabHTML.replace(/\s*/g, "");
			splitNums = removeWhite.split("");
			
			for( i = 0; i < splitNums.length; i++){
				var newSpan = new Element('span', {
					'class': 'num-'+splitNums[i] +' ie6_png_fix',
					'html': splitNums[i]
				});
				newSpan.inject($$("#numberCard td")[0]);
			}
			
			$('initialNum').setStyle('display', 'none');
		});
	}
});

/*** overlay mindow ***/
var Mindow = new Class({ 
	Implements: [Options],				   
	options: {
		overlayColor: '#000',
		opacity: 0.7,
		scrolling: false,
		isOpen: false,
		overlayPosition: 'fixed',
		overlayClickToClose: true,
		height: 400,
		width: 300,
		version: '0.4',
		className: 'mdowClass'
	},	
	initialize: function(source, options){
		// read in params
		this.source = source;
		this.setOptions(options);

		// determine scrolling
		(this.options.scrolling) ? this.scrolling = 'auto' : this.scrolling = 'hidden';
		// intialize the elements
		this.initHTML();
		
		// set trigger to fire mindow
		this.trigger = $(this.options.trigger);
		if(this.trigger){
			this.trigger.addEvent('click', function(e) {
				e = new Event(e).stop();
				this.openWindow();	
				this.loadWindow(this.source);
			}.bind(this));
		} else {
			this.openWindow();	
			this.loadWindow(this.source);			
		}
		// if you want window to be opened on load
		if (this.options.isOpen) {
		    this.openWindow();
		    this.loadWindow(this.source);
		}
		
		// move mindow when user scrolls
		window.addEvent('scroll', function(e) {
			if(this.options.overlayPosition == 'fixed') {
				if(this.mdowContainer.getStyle('display') == 'block') {
			    	this.setWindowScroll();
				}
			}
		}.bind(this));	
		// move mindow when user resizes 			
		window.addEvent('resize', function(e) {
			if(this.mdowContainer.getStyle('display') == 'block') {
		    	this.setWindowScroll();
			}
		}.bind(this));					

	},
	initHTML: function(){
		// create overlay		
		if(!$('mdowOverlay')){
			this.overlay = new Element('div', { 
				'id':'mdowOverlay',
				'styles': { 
					'height':0,
					'position': 'absolute',
					'top': 0,
					'left': 0,
					'z-index': 100000001,
					'visibility': 'visible',
					'width': '100%',
					'overflow': 'hidden',
					'cursor': 'pointer',
					'opacity':0,
					'backgroundColor': this.options.overlayColor
				}
			}).inject($(document.body));	
			
		} else {
			this.overlay = $('mdowOverlay');	
		}
		
		// attach click event on overlay to close overlay
		if(this.overlayClickToClose){
			this.overlay.addEvent('click', function(e) {
				e = new Event(e).stop();
				this.closeWindow();							
			}.bind(this));
		}
	
		// create mindow & close button
		if (!$('mdow')) {
		    this.mdowContainer = new Element('div', {
		        'id': 'mdowContainer',
		        'styles': {
		            'display': 'none',
					'position': 'absolute',
					'z-index':100000002,
					'top': '50%',
					'left': 0,
					'width': '100%',
					'height': 1,
					'overflow': 'visible',
					'visibility': 'visible'
		        }
		    }).inject($(document.body));
		    
			this.mindow = new Element('div', {
				'class': this.options.className,
				'id':'mdow', 
				'styles': {
					'display':'none',
					'position': 'absolute',
					'left': '50%',
					'background': '#fff'					
				}
            }).inject(this.mdowContainer);	
			
			this.btnclose = new Element('a',{
				'id':'mdowClose',
				'title':'close'
			}).inject(this.mindow);
			// make this only happen in IE6
		} else {
			this.mdowContainer = $('mdowContainer');
			this.mindow = $('mdow');	
			this.btnclose = $('mdowClose');
		}
		
		// attach event on close button
		this.btnclose.addEvent('click', function(e) {
			e = new Event(e).stop();
			this.closeWindow();							
		}.bind(this));
		
		this.btnclose.setStyle('display','none');			
	},
	loadWindow: function(source){
		// clear any html that might be in mindowso 
		this.mindow.set('html', '');
		this.setWindowScroll();
				
		this.mindow.setStyles({
		  	width: this.options.width,
		  	height: this.options.height,
			marginLeft: -(this.options.width / 2),
			//top: this.mindowTop,
			overflow: this.scrolling 
		});		
		// check to see if the souce is url or not
		if(source.indexOf('http') > -1){
			(this.scrolling == 'auto') ? this.iframescroll = 'yes' : this.iframescroll = 'no';
			this.myIframe = new Element('iframe', { 
				'id':'mdowIframe',
				'src': source,
				'frameborder': 0,
				'marginwidth': 0,
				'marginheight': 0, 
				'scrolling': this.iframescroll,
				'styles': { 
					'border': 0,
					'margin': 0,
					'width': this.options.width,
					'height': this.options.height
				}
			}).inject(this.mindow);	
		} else {
			// is div on page
			this.mindow.set('html', $(source).innerHTML);
		}
		
		// inject close button
		this.btnclose.inject(this.mindow);
	},
	setWindowScroll: function(){
		//this.overlayContainer.setStyle('top', window.getScroll().y);
		this.mdowContainer.setStyle('top', window.getScroll().y);
		(this.options.height > window.getSize().y) ? this.mindowTop = '30px' : this.mindowTop = ((window.getSize().y - this.options.height)/2);	
		this.mindow.setStyle('top',  this.mindowTop)
	},
	openWindow: function() {
		// show overlay
		this.overlay.setStyle('height', window.getScrollSize().y);
		this.overlay.tween('opacity',this.options.opacity);

		// show box
		this.mdowContainer.setStyle('display', 'block');
		this.mindow.setStyle('display','block');
		this.mindow.set('class',this.options.className);
		this.btnclose.setStyle('display','block');
	},
	closeWindow: function(){
	    // hide box
	    this.mdowContainer.setStyle('display', 'none');
		this.mindow.setStyle('display','none');
		this.mindow.set('class','');
		this.btnclose.setStyle('display', 'none');
		if (this.mindow.getElement('iframe')) {
			this.mindow.getElement('iframe').destroy();
		}
		// hide overlay
		this.overlay.set('tween', {
			onComplete: function(e) {
				if(this.overlay.getStyle('opacity') == 0) {
					this.overlay.setStyle('height', '0');
				}
			}.bind(this)
		});
		this.overlay.tween('opacity', '0');		
	}	
});

window.addEvent('domready', function() {
	
	$('navPreorder').addEvent('click', function(e) {
		var preOrderMindow = new Mindow('preorderPop', {
			className: 'preOrderMdow  ie6_png_fix',
			overlayColor: '#fff',
			scrolling: false,
			width: 924,
			height: 591
		});
		e.stop();
	});
	
	if ($('marqueePreorder')) {
		$('marqueePreorder').addEvent('click', function(e) {
			var preOrderMindow = new Mindow('preorderPop', {
				className: 'preOrderMdow ie6_png_fix',
				overlayColor: '#fff',
				scrolling: false,
				width: 924,
				height: 591
			});
			e.stop();
		});
	}
	// 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=FightNight-FightNightRound4&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=FightNight-FightNightRound4&locale=en_US&ref=EASports';
	}
	
	// show and up language drop down	
	$$('.langSelector')[0].getElement('a.activeLocale').addEvent('click', function(e) {
		e.stop();
		var parent = this.getParent();
		if(parent.hasClass('active')){
			parent.removeClass('active');
			$('langSelectoreDrop').setStyle('display','none');
		}
		else {
			parent.addClass('active');
			$('langSelectoreDrop').setStyle('display','block');
		}
	});

	// show nav drop down
	if ($$('.navDrop').length > 0) {
		$$('.navDrop').getElement('a.button').addEvent('click', function(e) {
			e.stop();
			this.toggleClass('active');
			var parent = this.getParent();
			if (this.hasClass('active')){
				parent.getElement('ul').setStyle('display','block');
			} else {
				parent.getElement('ul').setStyle('display','none');
			}
		});
		$$('.navDrop').getElement('ul li').addEvent('click', function(e) {
			this.getParent().setStyle('display','none');
		});
	};
});
