/* DOM READY EVENTS
Manages the GUS as well as the mooTools Dom effects.
*/

var mySlide;
var myLanguageSlide;

var loggedinMenuActive = false; //added because agegate kills dom tree in ie before ondomready can run

window.addEvent('domready', function(){
	var gusNavEAMenu = new quickNav('gus_ea','click');
	if (loggedinMenuActive) var gusNavWelcomeMenu = new quickNav('gus_welcome','click');
	//var mySliders = new menuSlider ({ gus_ea: 'gusEA', gus_welcome: 'gusWelcome' });
	
	if($type($('langOverlay'))){
		myLanguageSlide = new Fx.Slide('langOverlay').hide();
	}	
	if($type($('slideinLang'))){
		$('slideinLang').addEvent('click', function(e){
			e = new Event(e).stop();
			showLangLightbox();
		});
	}	
		
	if($type($('slideoutLang'))){
		$('slideoutLang').addEvent('click', function(e){
			e = new Event(e).stop();
			hideLangLightbox();
			myLanguageSlide.slideOut();
		});
	}
			
	//-vertical
	if($type($('handOverlay'))){
		mySlide = new Fx.Slide('handOverlay').hide();
	}	
	if($type($('slidein'))){
		$('slidein').addEvent('click', function(e){
			/*e = new Event(e);
			mySlide.slideIn();
			$('absoluteHand').setStyle("visibility", "visible");
			e.stop();*/
			omniLinkCall(this, 'signUp');
			slideNewsletter();
		});
	}
	if($type($('slideout'))){
		$('slideout').addEvent('click', function(e){
			e = new Event(e);
			resetFormClean();
			hideLightbox();
			mySlide.slideOut();
			document.getElementById('navFlashPlayer').deselectAllMenuItems();
			e.stop();
		});
	}
	if($type($('triggerBox'))){
		$('triggerBox').addEvent('click', function(e){
			//checkInfo();
			$('newsletterPen').setStyle("display", "none");
			$('newsletterPenHover').setStyle("display", "none");
			$('newsletterPenClick').setStyle("display", "block");

			newsletterReceipt();
			e = new Event(e).stop();			
		}.bind(this));
	}
});

function omniLinkCall(link,linkName) {
	setOmniValues(link,'o',linkName,'','','',0,'','');
}

// gus functions
function personaRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var personaLink = $('gusChangePersona').getProperty('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').getProperty('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').getProperty('href');
	this.document.location = loginLink + "&surl=" + returnTo; 
} 
function registerRedirect() {
	var returnTo = encodeURIComponent(this.document.location);
	var regLink = $('gus_register_link').getProperty('href');
	this.document.location = regLink + "&surl=" + returnTo; 
}

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

		this.menuEffect.hide();
		this.menu.style.visibility = "visible";
		if (eTrigger == "hover") {

			this.trigger.addEvent("mouseenter", function(e) {
				this.menuEffect.stop();		
				this.outerMenu.addClass('openTrigger');
				if(!this.trigger.hasClass('isActive')){
					this.trigger.addClass('isActive');
				}
				this.menuEffect.slideIn();
			}.bind(this));

			this.outerMenu.addEvent("mouseleave", function(e) {
				this.menuEffect.stop();										   
				this.menuEffect.slideOut().chain(function() {
					this.outerMenu.removeClass('openTrigger');
				}.bind(this));
				if(this.trigger.hasClass('isActive')){
					this.trigger.removeClass('isActive');
				}
			}.bind(this));

		} else if (eTrigger == "click") {

			this.trigger.addEvent("click", function(e) {
				e = new Event(e);													
				this.menuEffect.toggle();
				e.stop();
			}.bind(this));
		}
	}
});
/**
* Menuslider
*/
var menuSlider = new Class({
	activeSlider: null,
	chainedEffect: null,
	allSliders: new Object(),
	
	initialize: function(theSliders) {
		
		this.allSliders = theSliders;
				
		$each(theSliders, function(containerId,clickId) {
			if($(containerId) != null && $(clickId) != null){
				this.allSliders[clickId] = new Fx.Slide(containerId, {duration: 500, onComplete: this.fireChainedEffect.bind(this)});
				this.allSliders[clickId].hide();
				this.setSlider(clickId, this.allSliders[clickId]);
			}
		}.bind(this));
	},
	fireChainedEffect: function() {
		if(this.chainedEffect != null) {
			this.activeSlider = this.chainedEffect;
			this.activeSlider.toggle();
			this.chainedEffect = null;
		}	
	},
	setSlider: function(curId, curSlider){
		$(curId).addEvent('click', function(e){
			e = new Event(e);
			$(curSlider.element.id).setStyle("visibility","visible");
			if(this.activeSlider != null && this.activeSlider != curSlider){
				this.chainedEffect = curSlider;
				this.activeSlider.stop();
				this.activeSlider.slideOut();
			} else {
				this.activeSlider = curSlider;
				this.activeSlider.toggle();
			}
			e.stop();
		}.bind(this));	
	}
});


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 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 popWallpaper(url, width, height) {
   if(confirmLegal()){
      openCenteredWindow(url,'pop', width, height,'yes');
   }
}

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

/*************************************
   Confirm legal box for flash downloads
*************************************/

	function flashLegal(url) {
		if (confirmLegal()) {
			window.location=url;
		} 
	}

/* 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;
} 

/* FILM STRIP
 The following functions control the film strip for the home Media window,
 the news Articles, and the Dev Notes.
*/

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

		// 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+"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.addEvent('click', function(e) { this.setPage(e,1); }.bind(this));
		this.prevButton.addEvent('click', function(e) { this.setPage(e,-1); }.bind(this));	
	},

	setupEffect: function() {
		(this.myOptions.scrollDir == 'vertical') ? this.styleType = 'top' : this.styleType = 'left';
		this.pageSlider = new Fx.Style(this.filmStrip, this.styleType, {
			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.getElementSize();
	},

	getElementSize: function() {
		($type(this.myOptions.viewPortWidth)) ? this.viewPortWidth = this.myOptions.viewPortWidth : this.viewPortWidth = this.viewPort.getSize().size.x;
		($type(this.myOptions.viewPortHeight)) ? this.viewPortHeight = this.myOptions.viewPortHeight : this.viewPortHeight = this.viewPort.getSize().size.y;
		($type(this.myOptions.filmStripHeight)) ? this.filmStripHeight = this.myOptions.filmStripHeight : this.filmStripHeight = this.filmStrip.getSize().size.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.container.getElement(this.myOptions.numResults).value;
			this.pages = Math.ceil(this.numResults/this.itemPerPage);	
		}	
	},

	setPage: function(e, direction) {
		e = new Event(e);
		// Update curpage
		(direction == 1) ? this.curPage++ :	this.curPage--;

	// determine the pages new left value
		var filmstripScrollPosition;
		if(this.myOptions.scrollDir == 'vertical'){
			 filmstripScrollPosition = this.viewPortHeight * -(this.curPage);
		} else {
			filmstripScrollPosition = this.viewPortWidth * -(this.curPage);
		}
		this.pageSlider.stop();
		this.pageSlider.start(filmstripScrollPosition);

		// set the pagination controls
		this.setPaginationControls();
		e.stop();
	},

	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.curPage == (this.pages-1) || this.numResults == 0) ? 	this.nextButton.setStyle("visibility", "hidden") : this.nextButton.setStyle("visibility", "visible");
		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;	
		}
	}	
});

/* PREORDER POPUP
 The following functions control the pre-order flash popup.
 These functions respond to the external JS call from the Main Nav SWF.
*/

function openPreorderPopup(){
	$('popupViewer').setStyle("display", "block");
}

function closePreorderPopup(){
	$('popupViewer').setStyle("display", "none");
}
/* Lang Selector
 */
function showLangLightbox (){
	//document.documentElement.style.overflow = document.html.style.overflow = 'hidden';
	myLanguageSlide.slideIn();
	showLightbox(document.createElement('a'));
	$('absoluteLang').setStyle("visibility", "visible");		
	return false;	
}
function hideLangLightbox (){
	//document.documentElement.style.overflow = document.html.style.overflow = 'auto';	
	hideLightbox();
}
function setLangCookie(){
	var langCookieName = "gf2_lang";
	var langCookieValue = "en";
	var expiredays = 365;
 	
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = langCookieName + "=" + escape(langCookieValue) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	
	hideLightbox();
	myLanguageSlide.slideOut();
		
}
function checkLangCookie (){
	if($('overlay')) {
		clearTimeout(myLangTimerId);
		var langCookieName = "gf2_lang";
		var langCstart = document.cookie.indexOf(langCookieName+"=");
	  	if(langCstart==-1){
			showLangLightbox();
	   	}		
	}

}
/* NEWSLETTER FUNCTIONS 
 Functions that control the functionality of the newsletter.
 Expected Behavior: When a user clicks on the Newsletter link in the Main Nav SWF the newsletter
 opens up 'slides in' and lightbox is activated.
*/

function slideNewsletter(){
	mySlide.slideIn();
	$('newsletterPen').setStyle("display", "block");
	$('triggerBox').setStyle("display", "none");
	$('absoluteHand').setStyle("visibility", "visible");
	return false;
}

/* EMAIL/AGE VALIDATION
 Functions for the validation of the users birthday and email address. 
 Behaviour: If the user enters a valid email address and he/she is of valid age,
 move pen to Hover state and allow form submit.
*/
 
var valid_emailAddress = 0;
var valid_userAge = 0;

function checkEmail(){
	var str=document.newsLetterInfo.EmailAddr.value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	var container = document.getElementById("emailBoxWarning");
	
	if (filter.test(str)){
		/*$('newsletterPenHover').setStyle("display", "block");
		$('newsletterPen').setStyle("display", "none");*/
		container.style.visibility="hidden";
		container.style.display="none";
		
		valid_emailAddress = 1;
		formSubmit();
		
	}else{
		/*$('newsletterPenHover').setStyle("display", "none");
		$('newsletterPen').setStyle("display", "block");*/
		container.style.visibility="visible";
		container.style.display="block";
		
		valid_emailAddress = 0;
		formSubmit();
	}
}
function checkInfo(){
	if (document.layers||document.getElementById||document.all){
		return checkEmail();
	}else{
		return true;
	}
}
function onAgeSelect2(){
	// assemble the birthdate 
	var bdM = document.getElementById("ageSelector_month2").value;
	var bdD = document.getElementById("ageSelector_day2").value;
	var bdY = document.getElementById("ageSelector_year2").value;
	if(bdD.length>0 && bdM.length>0 && bdY.length>0){
		if (bdD.length==1){
			bdD = "0"+bdD;
		}
		var birthdayValue = escape(bdY + "-" + bdM + "-" + bdD + " 00:00:00.000");
		var birthday = (bdY + "/" + bdM + "/" + bdD);
		//send this value to the form
		$('BirthDate').value = birthdayValue;
		// now check the date
		checkAndActOnAge2(birthday);
	}
}
	
function checkAndActOnAge2(ageBirthdayValue){
	dtNow = new Date();
	dtBD = new Date(unescape(ageBirthdayValue));
	var requiredAge = 17;
	
	age = dtNow.getFullYear() - dtBD.getFullYear();
	if(dtNow.getMonth() < dtBD.getMonth()) age--;
	else if(dtNow.getMonth() == dtBD.getMonth() && dtNow.getDate() < dtBD.getDate()) age--;
	if(age < requiredAge){
		//not old enough
		valid_userAge = 0;
	} else {
		//old enough
		valid_userAge = 1;
	}	
}

function formSubmit(){	
	if(valid_emailAddress==1){
		$('newsletterPenHover').setStyle("display", "block");
		$('newsletterPen').setStyle("display", "none");
		$('triggerBox').setStyle("display", "block");		
	}else{
		$('newsletterPenHover').setStyle("display", "none");
		$('newsletterPen').setStyle("display", "block");
		$('triggerBox').setStyle("display", "none");
	}	
}

function newsletterReceipt(){
	if(valid_userAge==1){
		$('theHand').setStyle("display", "none");
		$('newsletterSuccess').setStyle("display", "block");
		$('newsletterSuccess').getElement('.closebutton').addEvent('click', function(e){
			mySlide.slideOut().chain(function(){
				$('newsletterSuccess').setStyle("display", "none");
				$('theHand').setStyle("display", "block");
				resetForm();
			});
			hideLightbox();
			e = new Event(e).stop();	
		}.bind(this));
		var myXhr = new XHR({method: 'post'});
		var formData = "emailAddr=" + $('emailBox').value + "&L_EA_Games_Godfather_HouseList=" + $('radioBox1').value + "&L_EA_Games_EA_Games_Main=" + $('radioBox2').value + "&birthDate=" + $('BirthDate').value;
		myXhr.send(document.newsLetterInfo.action, formData);
		
	}else{
		$('theHand').setStyle("display", "none");
		$('newsletterFail').setStyle("display", "block");
		$('newsletterFail').getElement('.closebutton').addEvent('click', function(e){
			mySlide.slideOut().chain(function(){ 
				$('theHand').setStyle("display", "block");	
				$('newsletterFail').setStyle("display", "none");
				resetForm();
			});
			hideLightbox();
			e = new Event(e).stop();	
		}.bind(this));
	}
	return false;
}

function resetForm(){
	$('newsletterPenClick').setStyle("display", "none");
	$('emailBox').value="";
	$('ageSelector_month2').value="";
	$('ageSelector_day2').value="";
	$('ageSelector_year2').value="";
}
function resetFormClean(){
	$('newsletterPen').setStyle("display", "none");
	$('newsletterPenHover').setStyle("display", "none");
	$('emailBox').value="";
	$('ageSelector_month2').value="";
	$('ageSelector_day2').value="";
	$('ageSelector_year2').value="";
}

function callIsSoundOnByDefault() {
	return document.getElementById('navFlashPlayer').isSoundOnByDefault();
}

function callPlaySound() {
	document.getElementById('navFlashPlayer').playSound();	
}

function callStopSound() {
	document.getElementById('navFlashPlayer').stopSound();
}



