function closeVideo() {
	history.back();
}

/*
function shareVideo() {
	var url = window.location.href;
	window.open(url, 'sendToAFriendWindow', 'menubar=no,status=no,toolbar=no,resizable=no,scrollbars=yes,width=410,height=320,titlebar=no,alwaysRaised=yes');
}
*/
function sendToAFriend(mode) {
	var url = '/us/sendtoafriend.jsp?mode=' + mode + '&url=';
	url += window.location.href;
	
	if (mode=="premiums") {
		url = "/us/premiums/sendtoafriendpremiums.jsp?mode=" + mode + "&url=";
		
		if (window.location.href.indexOf("section") < 0) {
			url += window.location.href + "?section=quiz";
		} else {
			url += window.location.href;
		}
		
		window.open(url, 'sendToAFriendWindow', 'menubar=no,status=no,toolbar=no,resizable=no,scrollbars=no,width=520,height=380,titlebar=no,alwaysRaised=yes'); 			
	} else {

		window.open(url, 'sendToAFriendWindow', 'menubar=no,status=no,toolbar=no,resizable=no,scrollbars=yes,width=440,height=320,titlebar=no,alwaysRaised=yes'); 	
	}
}

/*
Phone number validation
*/
function isInteger(s)
{
	var i;
	for (i=0; i<s.length; i++)
	{
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false; // current character is not a number
	}
	return true; // all characters are numbers
}

function validatePhone(formName)
{
	var digitsInPhoneNumber = 10;
	var phone = document.getElementById(formName).mobileNumber
	
	if ((phone.value==null)||(phone.value==""))
	{
		alert("Please enter your phone number");
		phone.focus();
		return false;
	}
	if (!isInteger(phone.value) || phone.value.length != digitsInPhoneNumber)
	{
		alert("Please enter a valid phone number (Format: 8885551234)");
		phone.focus();
		return false;
	}
	return true;
}

/*
Avatar download
*/
function downloadAvatar(avatarURL) {
	var url = '/us/becomeanmm/create/avatarpickup.jsp';
	if (avatarURL != "") { url += "?image=" + avatarURL }
	window.open(url, 'downloadAvatarWindow', 'menubar=no,status=no,toolbar=no,resizable=no,scrollbars=no,width=545,height=450,titlebar=no,alwaysRaised=yes'); 
}

function openWindow(URL, winname, winoptions) {
	winInfo = "location=no,status=no,menubar=no,resizable=yes";
	if(winoptions != ""){
		if(winoptions.charAt(winoptions.length - 1) != ",")
			{winoptions += ",";}
		if(winoptions.indexOf("scrollbars") == -1)
			{winInfo += ",scrollbars=yes";}
		winInfo = winoptions + winInfo;
	}	
	
	var theWindow = window.open(URL, winname, winInfo);
	theWindow.focus();
}

/*
 **********************************************************************************
 *  Fix IE background image flicker
 *  http://www.mister-pixel.com/
 **********************************************************************************
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/*
 **********************************************************************************
 *  Custom Events
 **********************************************************************************
 */
(function()
{
    /*
     *  Mouse Wheel Events
     *  http://andrewdupont.net/2007/11/07/pseudo-custom-events-in-prototype-16/
     */
    function wheel(event)
    {
        var realDelta;
        
        // normalize the delta
        if (event.wheelDelta) // IE & Opera
        {
            realDelta = event.wheelDelta / 120;
        }
        else if (event.detail) // W3C
        {
            realDelta = -event.detail / 3;
        }
        
        if (!realDelta) return;
        
        var customEvent = event.element().fire('mouse:wheel', {delta: realDelta});
        if (customEvent.stopped) event.stop();
    }
    
    document.observe('mousewheel', wheel);
    document.observe('DOMMouseScroll', wheel);
    
    /*
     *  Keyboard Events
     */
    function type(event)
    {
        var intendedAction;
        
        var keycode = event.which || event.keyCode;
	    var key = String.fromCharCode(keycode).toLowerCase();
	    
        if((key == 'x') || (key == 'c') || (keycode == Event.KEY_ESC))
		{
			intendedAction = 'close';
		}
		else if (keycode == Event.KEY_RETURN)
		{
		    intendedAction = 'submit';
		}
		
        if (!intendedAction) return;
        
        var customEvent = event.element().fire('keyboard:type', {action: intendedAction});
        if (customEvent.stopped) event.stop();
    }
    
    document.observe('keydown', type);
})();

/*
 **********************************************************************************
 *  Overlay - functionality from lightbox v2
 *  http://www.huddletogether.com/projects/lightbox2/
 **********************************************************************************
 */
var Overlay = Class.create({
    opacity: 0.525,
    duration: 0.2,
    
    initialize: function(manager)
    {
        this.manager = manager;
        
        this.overlay = new Element('div', {id: 'overlay', style: 'display: none'})
        $(document.body).insert(this.overlay);
        
        //this.onKeyboardType = this.onKeyboardType.bindAsEventListener(this);
    },  
    show: function()
	{
	    var bodyHeight = $(document.body).getHeight();
		var viewportHeight = $(document.viewport).getHeight();

        // stretch overlay to fill page
        this.overlay.setStyle({
            width: '100%',
            height: (bodyHeight > viewportHeight) ? bodyHeight + 'px' : viewportHeight + 'px'
        });
		
		// fade in
		new Effect.Appear(this.overlay, {
		    duration: this.duration,
		    from: 0.0,
		    to: this.opacity
        });
        
        //document.observe('keyboard:type', this.onKeyboardType);
	},	
	hide: function()
	{
	    document.stopObserving('keyboard:type', this.onKeyboardType);
	    
        new Effect.Fade(this.overlay, {duration: this.duration});
	},	
	onClick: function(event)
	{
	    this.manager.destroyUI();
	},
	onKeyboardType: function(event)
	{
	    if (event.memo.action == 'close')
	    {
	        this.manager.destroyUI();
	    }
	}
});

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if ((pos1==-1 || pos2==-1) ||
	(strMonth.length<1 || month<1 || month>12) ||
	(strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]) ||
	(strYear.length != 4 || year==0 || year<minYear || year>maxYear) ||
	(dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)) {
		document.getElementById('agegate-error').style.display = "block";
		document.getElementById('agecheck-inner').className = "inner-error";
		return false
	}
	return true
}

/*
 **********************************************************************************
 *  Age Gate Template
 **********************************************************************************
 */
var todaysDate = new Date();
var todaysYear = todaysDate.getFullYear();
var todaysMonth = (todaysDate.getUTCMonth() + 1); //months are numbered starting with 0 rather than 1
var todaysDay = todaysDate.getDate();
var AgeGateTemplate = Class.create({
    initialize: function(manager, data)
    {
		this.index = "/"
        this.manager = manager;
        this.data = Object.extend({
			URL : null
		}, data || {});
        //this.close = new Element('p', {id: 'close'}).insert(new Element('a', {href: '#'}).update('Close').observe('click', this.onCloseClick.bindAsEventListener(this)));
		//this.noClose = new Element('p', {id: 'close'}).insert(new Element('a', {href: '#'}).update('Close').observe('click', this.onCloseClick.bindAsEventListener(this)));
		
		// copy for the initial age gate screen	(with form now)
		this.header = new Element('h2', {id: 'enterbirthdate'}).update('Please enter your birthdate');
        this.paragraphone = new Element('p').update('Before you can continue, we need to verify your age.');
		
		this.birthDate = new Element('input', {type: 'text', name: 'birthDate', id: 'birthDate', maxlength: '10', style: 'position: relative;'});
		this.birthDateFormat = new Element('span').update(' (mm/dd/yyyy)');
		this.error = new Element('p', {id: 'agegate-error', style: 'display: none;'}).update('The date format should be mm/dd/yyyy');

		this.ageformsubmit = new Element('a', {id: 'formsubmit'}).update('Continue').observe('click', this.onSubmitClick.bindAsEventListener(this));
		
		this.ageform = new Element('form', {'name': 'agecheckform', id: 'agecheckform', method: 'post'}).observe('submit', this.onSubmitClick.bindAsEventListener(this)).insert(this.birthDate).insert(this.birthDateFormat).insert(this.error).insert(this.ageformsubmit);

		// copy for the "No" screen
		var underAgeMessage = 'We\'re sorry, but you\'re not eligible to access this area.';
		this.noHeader = new Element('h2', {id: 'sorry'}).update('Sorry');
        this.noParagraphone = new Element('p').update(underAgeMessage);
		this.noCloselink = new Element('a', {id:'ageclose'}).addClassName('button').update('Close this window').observe('click', this.onCloseClick.bindAsEventListener(this));
		this.noButtonDiv = new Element('div', {id:'agebuttons'}).addClassName('floatwrapper').insert(this.noCloselink);
        this.noInner = new Element('div', {id: 'agecheck-inner'}).addClassName('inner').insert(this.noHeader).insert(this.noParagraphone).insert(this.noButtonDiv)
		this.noCopy = new Element('div', {id: 'copy'}).insert(this.noInner);	
		if (Get_Cookie('underage'))
		{
			this.cookieHeader = new Element('h2', {id: 'sorry'}).update('Sorry');
			this.cookieParagraphOne = new Element('p').update(underAgeMessage);
			this.inner = new Element('div', {id: 'agecheck-inner'}).addClassName('inner').insert(this.cookieHeader).insert(this.cookieParagraphOne).insert(this.noButtonDiv);
	        this.copy = new Element('div', {id: 'copy', style: 'position: relative;'}).insert(this.inner);
		}
		else
		{
			this.inner = new Element('div', {id: 'agecheck-inner'}).addClassName('inner').insert(this.header).insert(this.paragraphone).insert(this.ageform);
	        this.copy = new Element('div', {id: 'copy'}).insert(this.inner);
        }

    },
	toElement: function()
    {
		this.container = new Element('div', {id: 'agecheck'}).addClassName('overlay').insert(this.copy);        
		return this.container;
    },
    destroy: function() {
		this.container.remove();
	},
    onCloseClick: function(event)
    {
        event.stop(); // prevent browser default click
        this.manager.destroyUI();
		window.location = this.index
    },
	onYesClick: function(event)
	{
		this.manager.destroyUI();
	},
	onSubmitClick: function(event)
	{
		var dt=document.agecheckform.birthDate;
		if (isDate(dt.value)==false)
		{
			dt.focus();
			return false;
		}

		// Age check form capture and validation
		// Assumptions:  13 years old is okay, 12 years old is not.
		
		var birthMonth = month; 
		var birthDay = day;
		var birthYear = year;
		var leap = 0;

		var bSuccess = false;
		
		//Check to see if they're 13
		if (todaysYear - birthYear > 13) {
			//alert("Success!  You're older than 13!");
			bSuccess = true;
			Set_Cookie("legalage", "1", "", "/");
			this.manager.destroyUI();
			if(this.data.URL!=null) window.location = this.data.URL;
		} else if (todaysYear - birthYear < 13) {
			//alert("Sorry, you're younger than 13.");
			event.stop(); // prevent browser default click
	        this.copy.remove();
			this.container.insert(this.noCopy);
			this.container.show(this.noCopy);
			Set_Cookie("underage", "1", 1, "/");
		} else if (todaysYear - birthYear == 13) {
			//Now we have to calculate month:
			if (todaysMonth - birthMonth > 0) {
				//alert("Success!  You're older than 13!");
				bSuccess = true;
				Set_Cookie("legalage", "1", "", "/");
				this.manager.destroyUI();
				if(this.data.URL!=null) window.location = this.data.URL;
			} else if (todaysMonth - birthMonth < 0) {
				//alert("Sorry, you're younger than 13");
				event.stop(); // prevent browser default click
		        this.copy.remove();
				this.container.insert(this.noCopy);
				this.container.show(this.noCopy);
				Set_Cookie("underage", "1", 1, "/");
			} else if (todaysMonth - birthMonth == 0) {
				//Now we have to calculate day:
				if (todaysDay - birthDay > 0) {
					//alert("Success!  You're older than 13!");
					bSuccess = true;
					Set_Cookie("legalage", "1", "", "/");
					this.manager.destroyUI();
					if(this.data.URL!=null) window.location = this.data.URL || index;
				} else if (todaysDay - birthDay < 0) {
					//alert("Sorry!");
					event.stop(); // prevent browser default click
			        this.copy.remove();
					this.container.insert(this.noCopy);
					this.container.show(this.noCopy);
					Set_Cookie("underage", "1", 1, "/");
				} else if (todaysDay - birthDay == 0) {
					//alert("Success!  You're 13!");
					bSuccess = true;
					Set_Cookie("legalage", "1", "", "/");
					this.manager.destroyUI();
					if(this.data.URL!=null) window.location = this.data.URL;
				}
			}
		}
		
		if (bSuccess) {
	    	var doc = document.getElementsByTagName('div');
			for (var i = 0; i < doc.length; i++){
			   if (doc[i].id == "game") {
			   	doc[i].style.display = "";
			   }
			}
		}

	},
	onNoClick: function(event)
	{
		event.stop(); // prevent browser default click
        this.copy.remove();
		this.container.insert(this.noCopy);
		this.container.show(this.noCopy);
	}
});

var OverlayTemplate = Class.create(AgeGateTemplate, {
	initialize: function(manager,container) {
		this.manager = manager;
		this.copy = $(container).show();
	}
});

/*
 **********************************************************************************
 *  Age Gate Manager
 **********************************************************************************
 */
var OverlayManager = {

    data: {}, // data cache
    onAfterClose: null,
    init: function()
    {
    	var verifyPage = $$('.verifyAge');
        var verifyLinks = $$('.verify');
		var takeoverLinks = $$('.takeover');

        if (verifyLinks.size() == 0 && verifyPage.size()==0 && takeoverLinks.size() == 0) return;
        
       	Event.observe(window,'load', function() {
			if (!Get_Cookie("legalage")) {
				this.overlay = new Overlay(this); // initialize overlay
				if(verifyPage.size()>0) this.onBodyLoad();
			}
		}.bindAsEventListener(this));
		if(verifyLinks.size()>0) verifyLinks.invoke('observe', 'click', this.onLinkClick.bindAsEventListener(this)); // hijack click event
		if(takeoverLinks.size()>0) takeoverLinks.invoke('observe', 'click', this.onTakeoverClick.bindAsEventListener(this)); // hijack click event
    },
    onLinkClick: function(event)
    {
        event.stop(); // prevent browser default click

		var element = event.element();
		this.linkPath = element.rel; // get link path from rel attribute
		
		if (this.data[this.linkPath] == null) // check if data already exists (use cached version)
        {
            this.data[this.linkPath] =  new AgeGateTemplate(this, {URL: this.linkPath});
        }

        this.buildUI();
    },
	onTakeoverClick: function(event)
    {
        event.stop(); // prevent browser default click

		var element = event.element();
		this.linkPath = element.rel; // get link path from rel attribute
		
		if (this.data[this.linkPath] == null) // check if data already exists (use cached version)
        {
            this.data[this.linkPath] =  new OverlayTemplate(this,this.linkPath);
        }

        this.buildUI();
    },
	onBodyLoad: function(event)
    {
		this.onAfterClose = function(){
			var doc = document.getElementsByTagName('div');
			for (var i = 0; i < doc.length; i++) {
				if (doc[i].id == "game") {
					doc[i].style.display = 'block';
				}
			}
		}

		this.linkPath = 'verifyAge';
		this.data[this.linkPath] =  new AgeGateTemplate(this);
        this.buildUI();
    },
	onFunctionCall: function(file) {
		this.linkPath = file;
		if (this.data[this.linkPath] == null) // check if data already exists (use cached version)
        {
            this.data[this.linkPath] =  new AgeGateTemplate(this, {URL: this.linkPath});
        }
        this.buildUI();
	},
    buildUI: function()
    {
        this.overlay.show();
        $(document.body).insert(this.data[this.linkPath]);
    },
    destroyUI: function()
    {
        this.overlay.hide();
        this.data[this.linkPath].destroy();
		if(typeof this.onAfterClose=='function') this.onAfterClose();
	}
};

document.observe('dom:loaded', OverlayManager.init.bind(OverlayManager));

var AgeGateCall = function(file_path) {
	OverlayManager.onFunctionCall(file_path)
}.bind(OverlayManager)

var myLightWindow = null;
var OpenFlash = function(options) {
	myLightWindow = new lightwindow();
	myLightWindow.activateWindow(options)
}

function redirectToHomepage()
{
	window.location = "/";
}