// browser sniff
var sniff =  {
	isIE: false,
	isIE6: false,
	isIE7: false,
	isIE8: false,
	isFFMac: false,
	isChrome3: false,
	isFF30: false,
	isOpera: false,
	init: function() {
		if (navigator.userAgent.indexOf("MSIE 6.0") != -1) {
			this.isIE6 = true;
		} else if (navigator.userAgent.indexOf("MSIE 7.0") != -1) {
			this.isIE7 = true;
		} else if (navigator.userAgent.indexOf("MSIE 8.0") != -1) {
			this.isIE8 = true;
		}
		if (this.isIE6 || this.isIE7 || this.isIE8) { this.isIE = true }
		if (navigator.userAgent.indexOf("Macintosh") != -1 && navigator.userAgent.indexOf("Firefox") != -1) {
			this.isFFMac = true;
		}
		if (navigator.userAgent.indexOf("Chrome") != -1 && (
				navigator.userAgent.indexOf("3.0.195.38") != -1 || 
				navigator.userAgent.indexOf("3.0.195.33") != -1 ||
				navigator.userAgent.indexOf("3.0.195.27") != -1 || 
				navigator.userAgent.indexOf("3.0.195.21") != -1 )) {
			this.isChrome3 = true;
		}
		if (navigator.userAgent.indexOf("Firefox") != -1 && (
				navigator.userAgent.indexOf("3.0.16") != -1 || 
				navigator.userAgent.indexOf("3.0.17") != -1  || 
				navigator.userAgent.indexOf("3.0.10") != -1 || 
				navigator.userAgent.indexOf("3.0.15") != -1 || 
				navigator.userAgent.indexOf("3.0.11") != -1 || 
				navigator.userAgent.indexOf("3.0.14") != -1 || 
				navigator.userAgent.indexOf("3.0.13") != -1 || 
				navigator.userAgent.indexOf("3.0.5") != -1  || 
				navigator.userAgent.indexOf("3.0.8") != -1  ||
				navigator.userAgent.indexOf("3.0.1") != -1  ||
				navigator.userAgent.indexOf("3.0.6") != -1  ||
				navigator.userAgent.indexOf("3.0.3") != -1  ||
				navigator.userAgent.indexOf("2.0.0.11") != -1  ||
				navigator.userAgent.indexOf("3.0.7") != -1  ||
				navigator.userAgent.indexOf("3.0.4") != -1  ||
				navigator.userAgent.indexOf("3.0") != -1  ||
				navigator.userAgent.indexOf("2.0.0.14") != -1  ||
				navigator.userAgent.indexOf("2.0.0.12") != -1  ||
				navigator.userAgent.indexOf("3.0.12") != -1  ||
				navigator.userAgent.indexOf("1.5.0.9") != -1  ||
				navigator.userAgent.indexOf("2.0.0.9") != -1  ||
				navigator.userAgent.indexOf("3.0.9") != -1  ||
				navigator.userAgent.indexOf("1.5.0.12") != -1  ||
				navigator.userAgent.indexOf("2.0.0.6") != -1  ||
				navigator.userAgent.indexOf("2.0") != -1  )) {
			this.isFF30 = true;
		}
		if (navigator.userAgent.indexOf("Opera") != -1 && (
				navigator.userAgent.indexOf("10.10") != -1 || 
				navigator.userAgent.indexOf("9.80") != -1  || 
				navigator.userAgent.indexOf("9.30") != -1 || 
				navigator.userAgent.indexOf("9.64") != -1 || 
				navigator.userAgent.indexOf("9.63") != -1   )) {
			this.isOpera = true;
		}
/* -- removed because default styles should overlook TypeKit styles
		if (this.isChrome3 || this.isFF30 || this.isOpera) {
			document.write('<link type="text/css" rel="stylesheet" media="screen" href="/lib/css/default.css">');
		}
*/		
	}
}
sniff.init();

// trace function for firebug
var trace = function(obj) {
	try {
		window.console.log(obj)
	} catch(err) {
		// made of fail
	}
}

// NOTE dart.interstitial_* is overridden by the server.
// ad call object
var dart =  {
	dartSite: null,
	dartZone: null,
	dartGenre: null,
	dartSubGenre: null,
	dartGlobalID: null,
	dartArticleID: null,
	dartESRB: null,
	dartTimestamp: null,
	dartEvent: null,
	dartRichMedia: false,
	roadBlock: false,
	indexCountdown: false,
	rightCountdown: false,
	leaderAdServed: false,
	rightAdServed: false,
	countdownAdServed: false,
	adCheckWait: 1500,
	interstitial_max_views: 20,
	interstitial_freq: 5,
	interstitial_duration: 25,
	interstitial_show_interstitial: true,
	interstitial_show_prestitial: true,
	checkAd: function(unit) {
		switch(unit) {
			case "leader":
				var adCheckLeader =  window.setTimeout(function() {
					var imgList = $A($('leaderboard').getElementsByTagName('img'));
					if (imgList.length != 0) {
						imgList.each(function(imgAt) {
							if (imgAt.src.indexOf("817-grey.gif") == -1) {
						    	dart.leaderAdServed = true;
						    }
						});
					} else if ( $('leaderboard').childNodes.length > 4) {
						dart.leaderAdServed = true;
					} else if ( $('leaderboard').select('iframe').length != 0) {
						try {
							$('leaderboard').select('iframe')[0].contentDocument.baseURI;
						}
						catch(err) {
							if (err) {
							    dart.leaderAdServed = true;
							}
						}
					}
					if (dart.leaderAdServed) {
						$('ad_bar').addClassName('show');
					}
				}, dart.adCheckWait);
			break;
			
			case "right":
				var adCheckRight =  window.setTimeout(function() {
					var imgList = $A($('ad').getElementsByTagName('img'));
					if (imgList.length != 0) {
						imgList.each(function(imgAt) {
							if (imgAt.src.indexOf("817-grey.gif") == -1) {
						    	dart.rightAdServed = true;
						    }
						});
					} else if ( $('ad').childNodes.length > 4) {
						dart.rightAdServed = true;
					} else if ( $('ad').select('iframe').length != 0) {
						try {
							$('ad').select('iframe')[0].contentDocument.baseURI;
						}
						catch(err) {
							if (err) {
							    dart.leaderAdServed = true;
							}
						}
					}
					if (dart.rightAdServed) {
						$('ad').addClassName('show');
					} else {
						$('ad').addClassName('hide');
					}
				}, dart.adCheckWait);
			break;
			
			case "countdown":
				(function(){
					if (dart.rightCountdown) {
						$('right_countdown').addClassName('show');
					}					
				}).delay(1);
			break;
			
			case "article":
				(function(){
					if (dart.roadBlock) {
						$('rb_ad').addClassName('show');
					} else {
						var is817 = false;
						$('rb_ad').select('img').each(function(imgAt) {
							if (imgAt.src == '817-grey.gif') {
								is817 = true;
							}
						});
						if (!is817) {
							$('rb_ad').addClassName('show');
						}
					}
				}).delay(1)
			break;
			
		  case "product":
				(function(){
					if (dart.roadBlock) {
						$('rb_ad').addClassName('show');
					} else {
						var is817 = false;
						$('rb_ad').select('img').each(function(imgAt) {
							if (imgAt.src == '817-grey.gif') {
								is817 = true;
							}
						});
						if (!is817) {
							$('rb_ad').addClassName('show');
						}
					}
				}).delay(1)
			break;

			case "index_countdown":		
				(function(){
					if (dart.indexCountdown) {
						$('index_countdown').addClassName('show');
					}					
				}).delay(2);
			break;
		}
	},
	adCall: function (site,zone,genre,subgenre,global_id,esrb,article_id,event) {
		this.dartSite = site;
		this.dartZone = zone;
		this.dartGenre = genre;
		this.dartSubGenre = subgenre;
		this.dartGlobalID = global_id;
		this.dartESRB = esrb;
		this.dartArticleID = article_id;
		this.dartEvent = event;
		this.dartTimestamp = Math.floor(Math.random() * 1000000000);
	}
}

var avp = {
	currentSkin: 1,
	changeSkin: function() {
		try {
			var skinClass = 'skinOne';
			if (avp.currentSkin == 1) {
				skinClass = 'skinTwo';
			} else if (avp.currentSkin == 2) {
				skinClass = 'skinThree';
			} else if (avp.currentSkin == 3) {
				skinClass = 'skinOne'
			}

			var url = '/bin/ads/sponsorships/avp/lib/img/'+skinClass;
			var body = $$("body")[0];
			body.className = skinClass;
			goog.ad(settings.pageType,skinClass);
			if (avp.currentSkin < 3) {
				avp.currentSkin++;
			} else {
				avp.currentSkin = 1;
			}
		} catch (error) {
			// fail
		}
	},
	clickableSkin: function() {
		Event.observe($('outer-wrap'), 'click', function(e){
			var currentNode = Event.element(e);
			if (currentNode.parentNode == $$('body')[0]) {
				avp.changeSkin();
				return false;
			}
		});
	}
}

var ads = {
	sponsorWrite: function(cssPath,urlPath) {
		var newLink = new Element('link',{
			rel: 'stylesheet',
			type: 'text/css',
			media: 'screen',
			href: cssPath
		});
		$$('head')[0].appendChild(newLink);
		if (urlPath) {
			ads.clickableSkin(urlPath);
		}
	},
	sponsorJSAdditions: function(jsPath) {
		var newScript = new Element('script',{
			type: 'text/javascript',
			src: jsPath
		});
		$$('head')[0].appendChild(newScript);
	},
	clickableSkin: function(urlPath) {
		if (!$('outer-wrap')) {
			window.setTimeout(function() {
				ads.clickableSkin(urlPath);
			}, 300);
		} else {
			Event.observe($('outer-wrap'), 'click', function(e){
				var currentNode = Event.element(e);
				if (currentNode.parentNode == $$('body')[0]) {			
					var newWindow = window.open(urlPath, '_blank');
					newWindow.focus();
					return false;
				}
			});
		}
	},
	writeVideoSkin: function(swfPath,height) {
		var videoCode = '<object width="100" height="'+height+'"> <param value="'+swfPath+'" name="video_ad" /><param name="mode" value="transparent"/><embed width="1000" height="'+height+'" wmode="transparent" type="application/x-shockwave-flash" src="'+swfPath+'"/></object>'; 
		$('ad_bar').update(videoCode);
	},
	changeSkin: function(style) {
		alert(style);
		try {
			var body = $$("body")[0];
			body.className = style;
		} catch (error) {
			// fail
		}
	},
	startTimer: function() {
		return;
		if (!$('leader_iframe')) { return;}
		var adTimer = window.setTimeout(function(){
			ads.refresh();
			ads.startTimer();
		},30000);
	},
	refresh: function() {
		// leaderboard refresh
		if($('leader_iframe')) {
			var newLeader = new Element ('iframe',{
				id: 'leader_iframe',
				src: $('leader_iframe').src,
				className: $('leader_iframe').className,
				height: 90,
				width: 728,
				frameBorder: 0,
				marginHeight: 0,
				marginWidth: 0,
				vspace: 0,
				hspace: 0,
				scrolling: 'no'
			});
			$('leader_iframe').remove();
			$('leaderboard').update(newLeader);			
		}
		
		// 300xwhatever refresh
		if($('tower_iframe')) {
			var newTower = new Element ('iframe',{
				id: 'tower_iframe',
				src: $('tower_iframe').src,
				className: $('tower_iframe').className,
				height: $('tower_iframe').height,
				width: $('tower_iframe').width,
				frameBorder: 0,
				marginHeight: 0,
				marginWidth: 0,
				vspace: 0,
				hspace: 0,
				scrolling: 'no'
			});
			$('tower_iframe').remove();
			$('ad').update(newTower);			
		}
	}
}

// search helper app
var search = {
	isInited: false,
	init: function() {
		if (!search.isInited) {
			if ($('searchField_label').visible()) {
				$('searchField_label').hide();
			}
			searchAsYouType.initialize(document.getElementById('searchField'), true);
			Event.observe('searchField','focus',this.focusApp);
			Event.observe('searchField','blur',this.blurApp);
		}
	},
	focusApp: function(e) {
		var target = Event.element(e);
		if (!$F(target)) {
			$('searchField_label').hide();
		}
	},
	blurApp: function(e) {
		var target = Event.element(e);
		if (!$F(target)) {
			$('searchField_label').show();
		}
	},
	checkIfBlank: function(){
		if(document.getElementById('searchField').value != ""){
			$('searchField_label').hide();
		}
	}
}

// login helper object
var login = {
	// Only query the server once for the prompt...
	login_form: null,
	promptLogin: function(type) {
		// Switch out the header text if necessary
		var content_title = "<h3>You need to be logged into GamePro.com</h3>";
		var login_title = "<h3>Login to GamePro.com</h3>";
		var title = (type && type == "content")? content_title : login_title;

		// Do we have the login form cached?
		if (!login.login_form) {
			new Ajax.Request('/login/ajax/get_login_prompt/', {
				method: 'post',
				parameters: {
					formType: type	
				},
				onSuccess: function(t) {
					// Cache it and pop it up
					login.login_form = t.responseText;
					dialog.show(title, login.login_form, {"onShow": login.focusLogin});
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				}
			});
		}
		else {
			// We do, just pop it up
			dialog.show(title, login.login_form, {"onShow": login.focusLogin});
		}
		return false;
	},
	focusLogin: function() {
		Form.Element.activate('username_login');
	},
	passwordReset: function() {
		new Ajax.Request('/login/ajax/password_email_form/', {
			onSuccess: function(t) {
				$('dialog-content').update(t.responseText);
				login.resizeDialog();
			}
		});
		return false;
	},
	sendPassReset: function() {
		new Ajax.Request('/login/ajax/password_reset/', {
			method: 'post',
			parameters: $('passReset').serialize(true),
			onFailure: function(t){
				_tools.ajaxBug(t);
			},
			onSuccess: function(t) {
				$('dialog-content').update(t.responseText);
				login.resizeDialog();
			}
		});
	},
	resizeDialog: function(){
		Lightview.resize({width: $('dialog-content').getWidth(), height: $('dialog-content').getHeight() });	
	},
	validatePassReset: function() {
		var errorMssg = [];
		if (!$F('password_1') || !$F('password_2')) {
			errorMssg.push('Please enter matching passwords in both supplied fields.');
		}
		if ($F('password_1') && $F('password_2')) {
			if ($F('password_1') != $F('password_2')) {
				errorMssg.push('Passwords do not match');
			}
		}
		if (errorMssg.length == 0) {
			$('passForm').submit();
		} else {
			var mssg = {
				"header": "There is an error",
				"bodyContent": ""
			}
			mssg.bodyContent += "<ol>";
			$(errorMssg).each(function(mssgAt) {
				mssg.bodyContent += "<li>" + mssgAt + "</li>";
			});
			mssg.bodyContent += "</ol>";
			util.talkbox($H(mssg).toJSON());
		}
	},
	toolBar: function() {
		new Effect.toggle('user_tools_menu','blind',{duration: .5});
	},
	status: function() {
		var rv = true;
		// IE sees our cookie as false; FF sees our cookie as "false"
		var login_cookie = Cookie.get("IDGE_LOGIN"); 
		if(login_cookie == null) rv = false;
		if(login_cookie == "") rv = false;
		if(login_cookie == "false") rv = false;
		if(login_cookie == false) rv = false;
		return rv;
	}
}

// wishlist
var wishlist =  {
	addList: function(globalID,type) {
		new Ajax.Request('/ajax/prodlist/add/', {
			method: 'post',
			parameters: {
				globalID: globalID,
				type: type
			},
			onSuccess: function(t) {
				util.talkbox(t.responseText.evalJSON());
				//If on Wishlist/Collections section, add games dynamically
				if($('wclistContainer')){
					var checkForError = $H(t.responseText.evalJSON()).toObject();
					if(checkForError.header.indexOf("There is an error") < 0){
						profile_edit.addToList(globalID, type);
					}
				}
			},
			onFailure: function(t) {
				_tools.ajaxBug(t);
			}
		});
	}
}

var polls =  {
	submitPoll: function(pollID) {
		var pollChecked = false;
		$('pollForm').select('input').each(function(itemAt){
		    if (itemAt.type == 'radio' && itemAt.checked) {
				pollChecked = true;
			}
		});
		if (!pollChecked) {
			$('pollError').show();
			new Effect.Pulsate('pollError',{
				from: .5
			})
			return false;
		}
		var formData = $('pollForm').serialize(true);
		new Ajax.Request('/ajax/polls/post/', {
			method: 'post',
			parameters: $('pollForm').serialize(true),
			onFailure: function(t){
				_tools.ajaxBug(t);
			},
			onSuccess: function(t) {
				polls.setResults(t.responseText);
			}
		});
	},
	viewResults: function(pollID) {
		new Ajax.Request('/ajax/polls/get_results/', {
			method: 'post',
			parameters: {
				pollID: pollID
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			},
			onSuccess: function(t) {
				polls.setResults(t.responseText);
			}
		});
	},
	setResults: function(markup) {
		$('pollForm').update(markup);
		$('pollForm').select('span.results').each(function(itemAt){
			var rawNum = parseInt(itemAt.id.split('_')[1]);
			var offSet = 10;
			if (rawNum == 100) {
				offSet = 0;
			}
		    var newNum = (rawNum + offSet) + '%';
		    var animateFunction = function () {
		        itemAt.morph('width: ' + newNum,{duration: 2});
				itemAt.update(itemAt.id.split('_')[1] + '%');
		    }
		    animateFunction();
		});
	}
}

// cookie helper app
var Cookie = {
  set: function(name, value, daysToExpire, domain) {
    var expire = '';
    var setdomain = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    if(domain != undefined) {
    	setdomain = "; path=/; domain=" + domain;
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + setdomain);
  },
  get: function(name) {
    var my_cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (my_cookie ? unescape(my_cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1,'.gamepro.com');
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1','.gamepro.com');
    return (Cookie.erase('_test') === '1');
  }
}

// new cookie helper app
var Cookies = Class.create({
    initialize: function(path, domain) {
        this.path = path || '/';
        this.domain = domain || null;
    },
    // Sets a cookie
    set: function(key, value, days) {
        if (typeof key != 'string') {
            throw "Invalid key";
        }
        if (typeof value != 'string' && typeof value != 'number') {
            throw "Invalid value";
        }
        if (days && typeof days != 'number') {
            throw "Invalid expiration time";
        }
        var setValue = key+'='+escape(new String(value));
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var setExpiration = "; expires="+date.toGMTString();
        } else var setExpiration = "";
        var setPath = '; path='+escape(this.path);
        var setDomain = (this.domain) ? '; domain='+escape(this.domain) : '';
        var cookieString = setValue+setExpiration+setPath+setDomain;
        document.cookie = cookieString;
    },
    // Returns a cookie value or false
    get: function(key) {
        var keyEquals = key+"=";
        var value = false;
        document.cookie.split(';').invoke('strip').each(function(s){
            if (s.startsWith(keyEquals)) {
                value = unescape(s.substring(keyEquals.length, s.length));
                throw $break;
            }
        });
        return value;
    },
    // Clears a cookie
    clear: function(key) {
        this.set(key,'',-1);
    },
    // Clears all cookies
    clearAll: function() {
        document.cookie.split(';').collect(function(s){
            return s.split('=').first().strip();
        }).each(function(key){
            this.clear(key);
        }.bind(this));
    }
});

// various global utility functions, stuff that gets run onload, etc.
var util =  {
	init: function() {
		util.checkGotMail();
		util.ie6Pwn();
		util.setKonami();
		util.setSubscription();
		util.releaseCal();
		util.fixFlash();
		search.checkIfBlank();
	},
	checkGotMail: function(){
		if(!$$('.mail.new')) return false;
		if($$('.mail.new').length > 0){
			new Effect.Pulsate($$('.mail.new')[0],{ pulses: 60, duration: 60, from: 0.65 });
		}
	},
	ie6Pwn: function() {
		if (sniff.isIE6 && Cookie.get('ie_alert') == null) {
			var newDiv = new Element('div',{id: 'ie6_alert'});
			var mssg = '<h2>You are using Internet Explorer 6.</h2>';
			mssg += '<p>You\'re using IE 6 and this site works best with FireFox and/or IE7. We suggest you upgrade or switch to one of the following: </p>';
			mssg += '<ul>';
			mssg += '<li class="ff"><a href="http://www.mozilla.com/en-US/products/download.html?product=firefox-2.0.0.12&os=win&lang=en-US">Mozilla Firefox</a></li>';
			mssg += '<li class="safari"><a href="http://www.apple.com/safari/download/">Apple Safari</a></li>';
			mssg += '<li class="ie7"><a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Microsoft Internet Explorer 7</a></li>';
			mssg += '<li class="ie8"><a href="http://www.microsoft.com/windows/products/winfamily/ie/ie8/readiness/Install.htm">Microsoft Internet Explorer 8 beta</a></li>';
			mssg += '<li class="close"><a href="##" onclick="util.hideIEMssg(); return false;">hide this message</a></li>';
			mssg += '</ul>';
			newDiv.update(mssg);
			$('wrapper').insertBefore(newDiv,$('content'));
		}
	},
	hideIEMssg: function() {
		Cookie.set('ie_alert','false',7,'.gamepro.com');
		new Effect.BlindUp('ie6_alert',{duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('ie6_alert').parentNode.removeChild($('ie6_alert'));
		},1000);
	},
	releaseCal: function(){
			if ($$('.release-cal').length != 0) {
				new tabClass($$('.release-cal')[0]);
			}
	},
	suckerfish: function() {
		if (!sniff.isIE) { return };
		$A(document.getElementsByClassName('suckerfish')).each(function(menuAt){
			menuAt.onmouseover = function() {
				//$(menuAt).addClassName('hover');
			}
			menuAt.onmouseout = function() {
				//$(menuAt).removeClassName('hover');
			}
		});	
	},	
	// getting basic non-secure user data
	userData: function() {
		if (Cookie.get('USER')) {
			return $H(Cookie.get('USER').evalJSON())._object;	
		} else {
			return null;
		}
	},
	userName: function() {
		if (util.userData()) {
			return util.userData().login_name;
		} else {
			return null;
		}
	},
	userNameID: function() {
		if (util.userData()) {
			return util.userData().login_name + ':' + util.userData().user_id;
		} else {
			return "";
		}
	},
	
	// makes dialog box for messaging users
	talkbox: function(h) {
		var content = $H(h).toObject();
		if ($('talkBox')) {
			$('talkHeader').update(content.header);
			$('talkTarget').update(content.bodyContent);
			new Effect.Highlight('talkTarget');
			return;
		}
		var newX = $('wrapper').getWidth() / 2 - 400 / 2;
		if (self.pageYOffset) {
			newY = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop) {
			newY = document.documentElement.scrollTop;
		}
		else if (document.body) {
			newY = document.body.scrollTop;
		}
		newY += 200;
		var newDiv = Builder.node('div',{
				id: 'talkBox', 
				className: 'app-window',
				style: 'top: ' + newY + 'px; left: ' + newX +'px; display: none;'},
			[Builder.node('a',
				{href: '#', className: 'close', onclick: 'util.removebox(); return false;'},
				[Builder.node('span','close')]
			)]
		);
		var content = $H(h).toObject();
		var talkHeader = Builder.node('h2',{id: 'talkHeader'}, content.header);
		var targetDiv = Builder.node('div',{id: 'talkTarget'}, '');
		$('wrapper').appendChild(newDiv);
		$('talkBox').appendChild(talkHeader);
		$('talkBox').appendChild(targetDiv);
		$('talkTarget').update(content.bodyContent);
		new Effect.Appear('talkBox', {duration: .5});
		util.toggleLeader('off');
		new Draggable('talkBox',{handle: 'talkHeader',zindex:940000});
		var highLightTimer = window.setTimeout(function(){
			new Effect.Highlight('talkTarget');
		},500);
	},
	removebox: function() {
		util.toggleLeader('on');
		new Effect.Fade('talkBox', {duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('talkBox').parentNode.removeChild($('talkBox'));	
		}, 500);
	},
	toggleLeader: function(mode) {
		if (!$('leaderboard')) { return false; }
		switch(mode) {
			case "off":
				if ($('leaderboard').select('iframe').length != 0) {
					$('leaderboard').hide();
				}
			break;
			case "on":
				if (!$('leaderboard').visible()) {
					$('leaderboard').show();
				}
			break;
		}
	},
	setLoading: function() {
		var mssg = {
			"header": 'Loading Content',
			"bodyContent": "<div class=\"loading\"><p>Loading</p></div>"
		}
		util.talkbox($H(mssg).toJSON());
	},
	setSaving: function() {
		var mssg = {
			"header": 'Saving Data',
			"bodyContent": "<div class=\"loading\"><p>Saving</p></div>"
		}
		util.talkbox($H(mssg).toJSON());
	},
	promptLogin: function() {
		login.promptLogin('content');
	},
	setKonami: function() {
		var kkeys = [];
		var konami = "38,38,40,40,37,39,37,39,66,65";
		Event.observe(window, 'keydown', function(e){
			kkeys.shift();
			kkeys[9] = e.keyCode;
			if ( kkeys.toString() == konami ) {
				try {
					Lightview.show({ href: 'http://www.youtube.com/v/v6TCQRrhMZo&hl=en&fs=1&color1=0x006699&color2=0x54abd6&border=1', rel: 'flash', options: { width: 800, height: 500 }});
					pageTracker._trackEvent('lulz', 'easter eggs', 'konami code');
				} catch (err) {
					window.location.href = "http://web.archive.org/web/19970127061931/www.gamepro.com/cgi-bin/w3com/start?gamepro+guest";
				}
			}
		});
	},
	setRetweetTrans: function() {
		//added so that in IE there isn't a white box that overlays the other share buttons
		///TweetMeMe does not include this when they create the iFrame
		if(!$$('.share-buttons .retweet').length > 0) { return;}
		$$('.share-buttons .retweet iframe').each(function(retweetFrame){
			retweetFrame.setAttribute('allowTransparency','allowTransparency');
		});
	},
	setSubscription: function() {
		//relies on carousel-min.js in pt-add-ons 
		if(!$$('.sub-box')[0]) { return };
		if(typeof(Carousel) == "undefined"){
			var head = document.getElementsByTagName('head')[0];
			var carousel_js = document.createElement("script");
			carousel_js.src =  "/lib/global/scripts/pt-add-ons/carousel-min.js";
			carousel_js.type = "text/javascript";
			//FF, Chrome, Safari
	        carousel_js.onload = function(){
				new Carousel('carousel-wrapper', $$('#carousel-content .slide'), $$('a.carousel-control'), {auto: true, circular: true, duration: .3, wheel: false});
			}
			//IE
			carousel_js.onreadystatechange = function() { if(carousel_js.readyState == 'complete' || carousel_js.readyState == "loaded") {
					new Carousel('carousel-wrapper', $$('#carousel-content .slide'), $$('a.carousel-control'), {auto: true, circular: true, duration: .3, wheel: false});
				}
			}
			head.appendChild(carousel_js);
		}
	},
	fixFlash: function(){
		//check to see if flash object contains a wmode parameter
		$$("#container object").each(function(thisObj){
			if(thisObj.innerHTML.indexOf('wmode') < 0){
				thisObj.down('embed').setAttribute('wmode','opaque');
				thisObj.insert({top:'<param name="wmode" value="opaque">'}).wrap('div');
				thisObj.up('div').insert(thisObj.up().innerHTML);
				thisObj.setStyle({display:'none'}).remove();
			}
		});
		$$("#container iframe").each(function(youtubeFrame){
			var searchForThis = youtubeFrame.getAttribute('src');
			if(searchForThis.indexOf('http://www.youtube.com/embed/') >= 0 && searchForThis.indexOf('wmode') < 0){
				if(searchForThis.indexOf('?') >= 0){
					youtubeFrame.setAttribute('src',searchForThis + '&wmode=opaque');
				} else {
					youtubeFrame.setAttribute('src',searchForThis + '?wmode=opaque');
				}
			}
		});
	}
}

var settings = {
	pagePlatform: null,
	pageType: null
}

// dev debug toolz
var _tools = {
	ajaxBug: function(t) {
		var overLay = new Element('div',{
			id: 'bugOverlay',
			style: 'z-index: 1000; padding: 20px; background: #FFF; position: absolute; left: 0; top: 0; width: ' + document.viewport.getWidth() + 'px; height: ' + document.viewport.getHeight() + 'px;'
		}).update(t.responseText);
		overLay.onclick = function() {
			$('bugOverlay').remove();
		}
		$$('body')[0].appendChild(overLay);
	},
	getQueryString: function (qname){
	  qname = qname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+qname+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
	}
}

var facebook = {
	user_initiated: false,
	loadingTries: 15,
	delay_ms: 3000,
	title: "<h3></h3>",

	slowLoad: function() {
		dialog.show(facebok.title
			,"<p>Please wait while Facebook initializes...</p>"
			,{"onShow": "facebook.toggle()"}
		);
	},

	setLoginCallback: function() {
		facebook.user_initiated = true;

		FB.Event.subscribe('auth.login', facebook.handleLoginCallback);
	},

	handleLoginCallback: function() {
		// Facebook Connect cookie just became active...
		if(login.status()) {
			// They probably were already logged into GP and just logged in to FB in a different window
			//document.location.reload();
		}
		else if(facebook.isUserWaiting()) {
			facebook.stopWaiting();
			// They are probably requesting login to GamePro by way of FB credentials
			// This link will return them using cgi.http_referer
			dialog.show(facebook.title
				,"<p>Redirecting to Facebook login page...</p>"
				,{"onShow": "document.location.href = '/login/facebook/';"}
			);
		}
	},

	setLinkCallback: function() {
		facebook.user_initiated = true;

		FB.Event.subscribe('auth.login', facebook.handleLinkCallback);
	},

	handleLinkCallback: function() {
		// Facebook Connect cookie just became active...
		if(login.status()) {
			// Check to see if the active user already has this Facebook account associated
			new Ajax.Request('/registration/ajax/',{
				method: 'post',
				parameters:  {
					type: 'checkFBLink'
				},
				onSuccess: function(t){
					var h = $H(t.responseText.evalJSON())._object;
					if(!h.success) {
						if(h.error_msg == "Not found.") {
							// Link the Facebook account
							facebook.link();
						}
						else {
							// Do nothing. FB <-> GP is invalid in some way
						}
					}
					else {
						// Do nothing. FB <-> GP link is active and valid
					}
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				}
			});
		}
		else if(facebook.isUserWaiting()) {
			facebook.stopWaiting();
			// They are probably requesting login to GamePro by way of FB credentials
			// This link will return them using cgi.http_referer
			dialog.show(facebook.title
				,"<p>Redirecting to Facebook login page...</p>"
				,{"onShow": "document.location.href = '/login/facebook/';"}
			);
		}
	},

	checkAndPromptForLink: function() {
		// Facebook Connect cookie just became active...
		if(login.status()) {
			// Check to see if the active user already has a Facebook account associated
			new Ajax.Request('/registration/ajax/',{
				method: 'post',
				parameters:  {
					type: 'hasFBLink'
				},
				onSuccess: function(t){
					var h = $H(t.responseText.evalJSON())._object;
					if(!h.success) {
						if(h.error_msg == "Not found.") {
							// Link the Facebook account
							var title = "<h3>Would you like to associate your GamePro and Facebook accounts?</h3>";
							var html = "<p><span class='fb_button fb_button_small' id='fb-login'>";
							html +=  "<a href='#' onclick='facebook.linkCheck(); return false;' class='fb_button_small'>";
							html +=   "<span id='fb_login_text' class='fb_button_text'>Connect with Facebook</span>";
							html +=  "</a>";
							html += "</span></p>";
							html += "<p>Opt out of this message in the future: <input type='checkbox' id='facebook_optout' onClick='facebook.optOut();'></p>";
							html += "<p><span id='optout_status'>&nbsp;</span></p>";
			 				dialog.show(title, html);
						}
						else {
							// Do nothing. FB <-> GP is invalid in some way
						}
					}
					else {
						// Do nothing. FB <-> GP link is active and valid
					}
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				}
			});
		}
	},

	optOut: function()
	{
		var el = $('facebook_optout');
		if(!el) return;
		$('optout_status').innerHTML = "Updating...";
		// Check to see if the active user already has a Facebook account associated
		new Ajax.Request('/registration/ajax/',{
			method: 'post',
			parameters:  {
				type: 'optOutFB',
				facebook_optout: el.checked
			},
			onSuccess: function(t){
				var h = $H(t.responseText.evalJSON())._object;
				if(!h.success)
					$('optout_status').innerHTML = "Sorry, there was an error saving your preference.";
				else
					$('optout_status').innerHTML = "Opt out preference updated.";
			},
			onFailure: function(t) {
				_tools.ajaxBug(t);
			}
		});
	},

	isUserWaiting: function() {
		return facebook.user_initiated;
	},
	
	stopWaiting: function() {
		facebook.user_initiated = false;
	},
	
	// They clicked the FB icon! What do we do?!?
	toggle: function() {
		//if(typeof FB == "undefined" && this.loadingTries--) return this.slowLoad();
		if(login.status()) {
			// They are logged into GamePro
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					// They are logged into Facebook as well
					// FIXME Check for a GP<->FB link first
					if(confirm("Would you like to logout of GamePro and Facebook?")) {
						dialog.show(facebook.title
							,"<p>Redirecting to log out page...</p>"
							,{"onShow": "document.location.href = '/login/out';"}
						);
						FB.logout();
					}
				}
				else {
					// They don't have an active FB session, so see if they want to login
					facebook.setLinkCallback();
					FB.login();
					dialog.hide();
				}
			});
		}
		else {
			// They don't have an active GP session
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					// They are logged into Facebook, so auto login or prompt for link / creation
					// FIXME Check for a GP<->FB link
					dialog.show(facebook.title
						,"<p>Redirecting to Facebook login page...</p>"
						,{"onShow": "document.location.href = '/login/facebook';"}
					);
				}
				else {
					// They don't have an active FB session either, so see if they want to login
					facebook.setLoginCallback();
					FB.login();
					dialog.hide();
				}
			});
		}
	},

	// They clicked the FB Connect icon (on the login dialog)
	status: function() {		
		if(login.status()) {
			/* If the FB Connect icon on the login dialog is showing, they are not logged in to GamePro
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					// FIXME Check for a GP<->FB link
					if(confirm("Would you like to logout?")) FB.logout();
				}
				else {
					// They don't have an active FB session
					facebook.setLinkCallback();
					FB.login();
					dialog.hide();
				}
			});
			*/
		}
		else {
			// They don't have an active GP session
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					dialog.hide();
					dialog.show(facebook.title
						,"<p>Redirecting to Facebook login page...</p>"
						,{"onShow": "document.location.href = '/login/facebook';"}
					);
				}
				else {
					// They don't have an active FB session either...
					facebook.setLoginCallback();
					FB.login();
					dialog.hide();
				}
			});
		}
	},

	// They clicked the FB Connect icon while being logged in to GamePro
	linkCheck: function() {
		if(login.status()) {
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					facebook.link();
				}
				else {
					// They don't have an active FB session
					facebook.setLinkCallback();
					FB.login();
					dialog.hide();
				}
			});
		}
		else {
			/* If the FB Connect icon on the profile page is showing, they are logged in to GamePro
			/*
			FB.getLoginStatus(function(response) {
				if(response.status && response.status == "connected") {
					// FIXME Check for a GP<->FB link
					dialog.show(facebook.title
						,"<p>Redirecting to Facebook login page...</p>"
						,{"onShow": "document.location.href = '/login/facebook';"}
					);
				}
				else {
					// They don't have an active FB session either...
					facebook.setLoginCallback();
					FB.login();
					dialog.hide();
				}
			});
			*/
		}
	},

	remove: function() {
		new Ajax.Request('/profile/ajax/remove_facebook/', {
			method: 'post',
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				var head = (!!h.success)? "<h3>Success!</h3>" : "<h3>Error!</h3>";
				var body = "<p>" + h.message + "</p>";
				if(!!h.success) {
					var fb_link_add = '<p><span class="fb_button fb_button_small" id="fb-login"><a href="#" onclick="facebook.linkCheck(); return false;" class="fb_button_small"><span id="fb_login_text" class="fb_button_text">Connect with Facebook</span></a></span></p>';
					$("link_facebook").update('<p>Facebook removed.</p>' + fb_link_add);
					$("pref_facebook").update('');
				}
				dialog.show(head, body);
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},

	link: function() {
		new Ajax.Request('/profile/ajax/link_facebook/', {
			method: 'post',
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				var head = (!!h.success)? "<h3>Success!</h3>" : "<h3>Error!</h3>";
				var body = "<p>" + h.message + "</p>";
				if(!!h.success) {
					var fb_link_remove = '<a href="#" class="button-large" onClick="facebook.remove(); return false;"><img src="/lib/img/icons/fb-icon-32x32.gif" class="icon" alt="Disconnect Facebook">Remove the Facebook account associated with this GamePro account</a>';
					$("link_facebook").update("<p>Facebook added! Be sure to set your preferences below.</p>" + fb_link_remove);
					facebook.prefUpdate();
				}
				dialog.show(head, body);
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},
	prefUpdate: function() {
		new Ajax.Request('/profile/ajax/build_facebook_prefs/', {
			method: 'post',
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				if(!!h.success) {
					var fb_pref_form = h.formblock;
					$("pref_facebook").update(fb_pref_form);
				}
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}

		});
	},

	/*
	// They clicked the log out link. See if we need to log out of facebook
	out: function() {
		FB.getLoginStatus(function(response) {
			if(response.status && response.status == "connected") {
				FB.logout();
			}
		});
	}
	*/
	
	validate_login: function(form) {
		var msg = "";
		function append_msg(m) {
			if(!m || !m.length || m.length == 0) return;
			if(msg.length == 0) msg = m;
			else msg += "<br>" + m;
		}
		if($F("username_login").length < 1) {
			append_msg("Please provide a username.");
		}
		if($F("login_password").length < 1) {
			append_msg("Please provide a password.");
		}
		if(msg.length != 0) {
			var title = "<h3>Please correct the following:</h3>";
			var html = "<p>" + msg + "</p>"; 
			dialog.show(title, html);
			return false;
		}
	
		reg.verifyLoginAndSubmit(form, continue_registration);
		return false;
	},
	
	validate_registration: function(form) {
		var msg = "";
		function append_msg(m) {
			if(!m || !m.length || m.length == 0) return;
			if(msg.length == 0) msg = m;
			else msg += "<br>" + m;
		}
		if(!$("tos").checked) {
			append_msg("Please argee to the terms of service.");
		}
		if($F("username").length < 1) {
			append_msg("Please provide a username.");
		}
		if(msg.length != 0) {
			var title =	"<h3>Please correct the following:</h3>";
			var html = "<p>" + msg + "</p>"; 
			dialog.show(title, html);
			return false;
		}
	
		reg.checkUserNameAndSubmit(form, continue_registration);
		return false;
	},
	
	populateEmail: function()
	{
		if(confirm("Would you like to use your Facebook email address on GamePro?")) {
			// Elevate email permissions
			FB.login(facebook.populateEmailCB, {"scope": "email"});
		}
	},

	populateEmailCB: function(response) {
		FB.api('/me', function(response) {
				if(typeof(response.email) != "undefined" && response.email.length > 0) {
			 		// They successfully set their email
					$("email").value = response.email;
					// Are they logged in to GamePro? See if they want to link GP <-> FB accounts
		 			if(login.status()) {
		 				facebook.checkAndPromptForLink();
		 			}
				}
				else {
					var title = "<h3>Error!</h3>";
					var html = "<p>We were unable to set your email address from Facebook.</p>"
					dialog.show(title, html);
				}
			});
	},

	enableAutoShare: function() {
		// Elevate publish permissions
		FB.login(facebook.enableAutoShareCB, {"scope": "publish_stream"});
	},

	enableAutoShareCB: function(response) {
		// We'll check the permission before each auto share item,
		// so just accept whatever FB sends back
	},

	getUserReviewData: function(review_id) {
		var rv = {
			prompt: "Share your GamePro user review on Facebook",
			name: "",		// "<name> Review"				// FB:name
			og_name: "",									// FB:name (opt'l)
			caption: "",	// "<title> <score>"			// FB:caption
			link: "",		// <meta property="og:url".. 	// FB:link
			picture: null,	// <meta property="og:image"..	// FB:picture
			description: "",								// FB:description
			message: "Read my review of "	// <name>		// FB:message
		}

		// Scan the page's meta tags
		var metas = document.getElementsByTagName("meta");
		for(var i = 0; i < metas.length; i++) {
			if(metas[i].getAttribute("property") == "og:url") {
				rv.link = metas[i].getAttribute("content");
			}
			if(metas[i].getAttribute("property") == "og:image") {
				rv.picture = metas[i].getAttribute("content");
			}
		}

		// Parse the DOM for product title and review title, score, and text
		var cont = $("review_" + review_id);
		var titles = cont.select("h4.title > div.hidden > ul.titles")[0];
		rv.name = titles.select("li.product")[0].innerHTML;
		rv.caption = titles.select("li.review")[0].innerHTML;
		rv.message += rv.name + " on GamePro";
		rv.name += " Review";

		// Append the review score
		rv.caption += " " + cont.select("ul.stats > li.label > span")[0].innerHTML;
		text_el = cont.select("div.review-body > p");
		text_el.each(function(node){
			// Append all the glorious p tags together...
			rv.description += node.innerHTML + " ";
		});

		return rv;
	},

	getBlogData: function(blog_id) {
		var rv = {
			prompt: "Share your GamePro blog on Facebook",
			name: "",								// FB:name
			og_name: "",							// FB:name (opt'l)
			caption: "",							// FB:caption
			link: document.location.href,			// FB:link
			picture: null,							// FB:picture
			description: "",						// FB:description
			message: "Read my blog on GamePro: "	// FB:message
		}

		// Parse the DOM for blog title, blog blurb, and blog date
		var cont = $$("div.user-blog > ul.blog-head").first();
		rv.name = cont.select("li.title")[0].innerHTML;
		rv.description = cont.select("li.hidden > div.blog-blurb")[0].innerHTML;
		rv.caption = cont.select("li.date").toArray();	// [0]=created [1]=edited
		rv.caption = rv.caption[rv.caption.length - 1].innerHTML;

		// Append blog title to user editable message
		rv.message = rv.message + rv.name;

		// Strip off paremters and anchors
		rv.link = rv.link.split("#")[0].split("?")[0];

		// Is this the POST commit page?
		if(rv.link.substr(-12) == "/postinsert/")
			rv.link = rv.link.replace("postinsert", "post/" + blog_id);
		return rv;
	},

	getCommentData: function(comment_type, comment_id) {
		var rv = {
			prompt: "Share your GamePro comment on Facebook",
			name: "",			// <meta name="title"...		FB:name
			og_name: "",		// <meta name="og:title"...		FB:name (opt'l)
			caption: "",		// <meta name="description"...	FB:caption
			link: "",			// <meta property="og:url"...	FB:link
			picture: "",		// <meta property="og:image"...	FB:picture
			description: "",	// DOM:comment_<id> > cont... 	FB:description
			message: "I just commented on " // <name>			FB:message
		}

		// Scan the page's meta tags for a base line
		var metas = document.getElementsByTagName("meta");
		for (var i = 0; i < metas.length; i++) {
			if (metas[i].getAttribute("name") == "title") {
				rv.name = metas[i].getAttribute("content");
			}
			if (metas[i].getAttribute("property") == "og:title") {
				rv.og_name = metas[i].getAttribute("content");
			}
			if (metas[i].getAttribute("name") == "description") {
				rv.caption = metas[i].getAttribute("content");
			}
			if (metas[i].getAttribute("property") == "og:url") {
				rv.link = metas[i].getAttribute("content");
			}
			if (metas[i].getAttribute("property") == "og:image") {
				rv.picture = metas[i].getAttribute("content");
			}
		}

		// OpenGraph data takes precedence
		if(rv.og_name.length > 0) {
			//caption = name;
			rv.name = rv.og_name;
		}
		rv.message = rv.message + rv.name + " on GamePro";

		// Specific comment type tweaks
		switch(comment_type) {
			case "user_review":
				// Parse the DOM for product title, review title, and review score
				var titles = $$("div.review > h4.title > div.hidden > ul.titles").first();
				var game = titles.select("li.product")[0].innerHTML;
				rv.caption = titles.select("li.review")[0].innerHTML;
				rv.message = "I just commented on a " + game + " User Review on GamePro";
				// Append the review score
				rv.caption += " " + $$("div.review > ul.stats > li.label > span").first().innerHTML;
			break;
			case "user_blog":
				rv.name = $$("ul.blog-head > li.title").first().innerHTML.stripTags();
				rv.caption = $$("ul.blog-head > li.hidden > div.blog-blurb").first().innerHTML.stripTags();
				rv.message = "I just commented on " + rv.name + " on GamePro";
				// No pictures, please!
				rv.picture = "";
			break;
			default: // Article, review, video and comments
			break;
		}

		// No OpenGraph link available; peal off parameters and anchors
		if(rv.link == "") rv.link = document.location.href.split("#")[0].split("?")[0];

		// Append the comment_id as a parameter for the server
		rv.link += "?show_comment=" + comment_id;
		// Append the comment_id as an anchor for the client
		rv.link += "#comment_" + comment_id;

		if(rv.description == "") {
			// Grab the actual comment text from the DOM
			var comment_cont = $("comment_" + comment_id);
			var comment_el = comment_cont.select("div.comment-body > p");
			comment_el.each(function(node){
				// Append all the glorious p tags together...
				rv.description += node.innerHTML + " ";
			});
		}
		rv.description = "Comment: " + rv.description;

		return rv;
	},

	/* Facebook Feed Form layout:
	  |--------------------------------------------------------|
	  | Publish this post to your FB Wall?                     |
	  |--------------------------------------------------------|
	  | |----------| Feed Form Prompt                          |
	  | | Facebook |                                           |
	  | | profile  | |---------------------------------------| |
	  | | picture  | | Message text input                    | | 
	  | |----------| |                                       | |
	  |              |---------------------------------------| |
	  |              |---------| Link Name                     |
	  |              | Link    | Link Caption                  |
	  |              | Picture | Link Description (300 chars.  |
	  |              | (opt'l) | shown with 1,000 being the    |
	  |              |---------| maximum allowed)...           |
	  |                         See More                       |
	  |--------------------------------------------------------|
	  |                                   | Publish | | Skip | |
	  |--------------------------------------------------------|
	 */

	// Share a user's comments on Facebook (one-off feed form version)
	shareComment: function(comment_type, comment_id) {
		if(!comment_type || !comment_id || comment_type.length < 1 || comment_id.length < 1) {
			dialog.show("<h3>Error</h3>", "<p>Sorry, but we were unable to share this comment on Facebook at this time.</p>");
			return false;
		}

		var prompt = "Share your GamePro comment on Facebook";
		var data = facebook.getCommentData(comment_type, comment_id);
		facebook.publishItem(prompt, data.message, data.name, data.caption, data.description, data.picture, data.link);
		return false;
	},

	// Share a user's blog on Facebook (one-off feed form version)
	shareBlog: function(blog_id) {
		if(!blog_id || blog_id.length < 1) {
			dialog.show("<h3>Error</h3>", "<p>Sorry, but we were unable to share this blog on Facebook at this time.</p>");
			return false;
		}
		var data = facebook.getBlogData(blog_id);
		facebook.publishItem(data.prompt, data.message, data.name, data.caption, data.description, data.picture, data.link);
		return false;
	},

	// Share a user's review on Facebook (one-off feed form version)
	shareReview: function(review_id) {
		if(!review_id || review_id.length < 1) {
			dialog.show("<h3>Error</h3>", "<p>Sorry, but we were unable to share this user review on Facebook at this time.</p>");
			return false;
		}
		var data = facebook.getUserReviewData(review_id);
		facebook.publishItem(data.prompt, data.message, data.name, data.caption, data.description, data.picture, data.link);
		return false;
	},

	// One-off feed form version (prompts the user)
	publishItem: function(prompt, message, name, caption, description, picture, link) {
		var max_length = 400;

		// Facebook nukes content within tags, so do it nicely instead
		description = description.replace(/<br>/g,' ');
		description = description.stripTags();
		// Clean up whitespace at the beginning and end
		description = description.strip();
		// Keep it a sane length...
		description = description.substr(0,max_length);

		// This is ghetto, but in-line or non-JSON format could cause problems
		if(picture != null && picture.length > 0)
			var attachment = {
				'name': name,
				'caption': caption,
				'description': description,
				'href': link,
				'media': [{ 'type': 'image', 'src': picture, 'href': link}]
			};
		else
			var attachment = {
				'name': name,
				'caption': caption,
				'description': description,
				'href': link
			};

		// Show the user the publishing UI
		FB.ui({'method': 'stream.publish',
					'display': 'popup',
					'message': message,
					'attachment': attachment,
					'action_links': [{'text': name, 'href': link}],
					'user_message_prompt': prompt
				}
			 	,function(response) {
			 		// If they posted, see if they want to link GP <-> FB accounts
			 		if(response && response.post_id) {
			 			// Are they logged into GamePro?
			 			if(login.status()) {
			 				facebook.checkAndPromptForLink();
			 			}
			 		}
		 	}
		 );
	},

	// Auto version (publishes without user intervention)
	publish: function(message, name, caption, description, picture, link) {
		var max_length = 400;

		// Facebook nukes content within tags, so do it nicely instead
		description = description.replace(/<br>/g,' ');
		description = description.stripTags();
		// Clean up whitespace at the beginning and end
		description = description.strip();
		// Keep it a sane length...
		description = description.substr(0,max_length);

		// This is ghetto, but in-line or non-JSON format could cause problems
		if(picture != null && picture.length > 0)
			var attachment = {
				'name': name,
				'caption': caption,
				'description': description,
				'href': link,
				'media': [{ 'type': 'image', 'src': picture, 'href': link}]
			};
		else
			var attachment = {
				'name': name,
				'caption': caption,
				'description': description,
				'href': link
			};

		// Publish directly to Facebook without user intervention
		var action_links = [{'text': name, 'href': link}];
		var params = {
			method: "stream.publish",
			attachment: attachment,
			message: message,
			action_links: action_links
		};
		FB.api(params, function(response) { /*console.dir(response);*/ });
	},

	streamInput: function(user_content_type, sub_type, description, id) {
		new Ajax.Request('/profile/ajax/get_facebook_prefs/', {
			method: 'post',
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				// Should we "auto" publish to their stream?
				if(user_content_type == "comments" && h.comments == "always"
					|| user_content_type == "blogs" && h.blogs == "always"
					|| user_content_type == "user-reviews" && h.reviews == "always") {
					switch(user_content_type) {
						case "comments":
							var data = facebook.getCommentData(sub_type, id);
							facebook.publish(data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
						case "user-reviews":
							var data = facebook.getUserReviewData(id);
							facebook.publish(data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
						case "blogs":
							var data = facebook.getBlogData(id);
							facebook.publish(data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
					}
				}
				// Should we feed form to their stream?
				else if(user_content_type == "comments" && h.comments == "prompt"
					|| user_content_type == "blogs" && h.blogs == "prompt"
					|| user_content_type == "user-reviews" && h.reviews == "prompt") {
					switch(user_content_type) {
						case "comments":
							var data = facebook.getCommentData(sub_type, id);							
							facebook.publishItem("Publish your comment to Facebook?", data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
						case "user-reviews":
							var data = facebook.getUserReviewData(id);
							facebook.publishItem("Publish your user review to Facebook?", data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
						case "blogs":
							var data = facebook.getBlogData(id);
							facebook.publishItem("Publish your blog to Facebook?", data.message, data.name, data.caption, data.description, data.picture, data.link);
						break;
					}
				}
			},
			onFailure: function(t){
				_tools.ajaxBug(t);
			}
		});
	},

	updatePrefs: function() {
		var comments = $RF("facebook_prefs", "fb_comments");
		var reviews = $RF("facebook_prefs", "fb_reviews");
		var blogs = $RF("facebook_prefs", "fb_blogs");
		if(comments == null || reviews == null || blogs == null) {
			dialog.show("<h3>Error!</h3>", "<p>Please make a selection for each content type.</p>");
		}
		else {
			new Ajax.Request('/profile/ajax/set_facebook_prefs/', {
				method: 'post',
				parameters:  {
					comments: comments,
					reviews: reviews,
					blogs: blogs
				},
				onSuccess: function(t) {
					var h = $H(t.responseText.evalJSON()).toObject();
					var head = (!h.success)? "<h3>Error!</h3>" : "<h3>Success!</h3>";
					var body = "<p>" + h.message + "</p>";
					dialog.show(head, body);
				},
				onFailure: function(t){
					_tools.ajaxBug(t);
				}
			});
			if(comments == "always" || reviews == "always" || blogs == "always") {
				facebook.enableAutoShare();
			}
		}
		return false;
	}
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

var subscribe = {
	failCount: 0,
	errorText: "",
	errorElements: [],
	errorListCheck: function(el) {
		if (subscribe.errorElements.indexOf(el) == -1) {
			subscribe.errorElements.push(el);
		}
	},
	clearEmailInput: function(){
		$$('.email-row label')[0].hide();
	},
	restoreEmailInput: function(){
		if($F('email') == ""){
			$$('.email-row label')[0].show();
		}
	},
	subButton: function(type) {
		var target = $('subSubmit');
		switch (type) {
			case "off":
				target.onclick = function() {};
			break;
			case "on":
				target.onclick = function() {
					subscribe.newsletter();
				}
			break
		}
	},
	newsletter: function() {
		// Reset the validation state
		subscribe.subButton("off");
		subscribe.failCount = 0;
		subscribe.errorText = "";
		subscribe.errorElements = [];
		subscribe.errorClear();
		if(!$F('email')) {
			subscribe.failCount++;
			subscribe.errorListCheck($('email'));
			subscribe.errorText += "<li>Please enter an email address.</li>";
		}
		if($F('email') && ($F('email').indexOf("@") == -1 || $F('email').indexOf(".") == -1)) {
			subscribe.failCount++;
			subscribe.errorListCheck($('email'));
			subscribe.errorText += "<li>Please enter an valid email address.</li>";
		}
		if(!$("newsletter_daily").checked && !$("newsletter_weekly").checked) {
			subscribe.failCount++;
			subscribe.errorListCheck($('newsletter'));
			subscribe.errorText += "<li>Please select a newsletter frequency.</li>";
		}
		if(subscribe.failCount > 0) subscribe.subError();
		else {
			new Ajax.Request('/registration/ajax/', {
				method: 'post',
				parameters: {
					type: 'newsletter',
					email: $F('email'),
					daily: $("newsletter_daily").checked? $("newsletter_daily").value : "",
					weekly: $("newsletter_weekly").checked? $("newsletter_weekly").value : ""
				},
				onSuccess: function(t) {
					var h = $H(t.responseText.evalJSON()).toObject();
					var head = (!h.success)? "<h3>Error!</h3>" : "<h3>Success!</h3>";
					var body = "<p>" + h.message + "</p>";
					dialog.show(head, body);
				},
				onComplete: function(t) {
					subscribe.subButton("on");
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				}
			});
		}
	},
	subError: function() {
		subscribe.errorMark();
		var message =  {
			"header": "There is an error",
			"bodyContent": "<ol>" + subscribe.errorText + "</ol><p><a href=\"#\" onclick=\"util.removebox(); return false;\">Close this window to correct and continue</a></p>"
		}
		util.talkbox($H(message).toJSON());
		subscribe.subButton("on");
	},
	errorMark: function() {
		$A(subscribe.errorElements).each(function(el){
			if(!!el) {
				var labelList = subscribe.labelList();
				labelList.each(function(label) {
					if(label.getAttribute("for") == el.getAttribute("id")) {
						label.addClassName('error');
					}
				});
				el.addClassName('error')
			}
		});
	},
	errorClear: function() {
		$A($('subForm').getElementsByClassName("error")).each(function(el){
			el.removeClassName("error");
		});
	},
	labelList: function() {
		return $A($('subForm').getElementsByTagName('label'));
	},
	update: function(checkEmail) {
		new Ajax.Request('/registration/ajax/', {
			method: 'post',
			parameters: {
				type: 'newsletter_update',
				email: $F('email'),
				emailcheck: $F('emailcheck'),
				daily: $("newsletter_daily").checked? $("newsletter_daily").value : "",
				weekly: $("newsletter_weekly").checked? $("newsletter_weekly").value : ""
			},
			onSuccess: function(t) {
				var h = $H(t.responseText.evalJSON()).toObject();
				var head = (!h.success)? "<h3>Error!</h3>" : "<h3>Success!</h3>";
				var body = "<p>" + h.message + "</p>";
				dialog.show(head, body);
			},
			onComplete: function(t) {
				subscribe.subButton("on");
			},
			onFailure: function(t) {
				_tools.ajaxBug(t);
			}
		});
	}
};

var dialog = {
	options: {},
	init: function() {
		dialog.initDOM();
//		dialog.initJS();
//		dialog.initCSS();
		dialog.initOptions();
	},

	initDOM: function() {
		if(!$('dialogBox')) {
			var body = document.getElementsByTagName('body')[0];
			var box = document.createElement("div");
			box.setAttribute("id", "dialogBox");
			box.style.display = "none";
			var content = document.createElement("div");
			content.setAttribute("id", "dialog-content");
			box.appendChild(content);
			body.appendChild(box);
		}
	},
/*
	initCSS: function() {
		var head = document.getElementsByTagName('head')[0];
		var lightview_css = document.createElement("link");
		lightview_css.setAttribute("type", "text/css");
		lightview_css.setAttribute("rel", "stylesheet");
		lightview_css.setAttribute("media", "screen,projection");
		lightview_css.setAttribute("href", "/lib/global/css/lightview/lightview.css");
		head.appendChild(lightview_css);

		var dialog_css = document.createElement("link");
		dialog_css.setAttribute("type", "text/css");
		dialog_css.setAttribute("rel", "stylesheet");
		dialog_css.setAttribute("media", "screen,projection");
		dialog_css.setAttribute("href", "/lib/css/dialogbox.css");
		head.appendChild(dialog_css);
	},

	initJS: function() {
		if(typeof(Lightview) == "undefined") {
			var head = document.getElementsByTagName('head')[0];
			var dialog_js = document.createElement("script");
			dialog_js.setAttribute("type", "text/javascript");
			dialog_js.setAttribute("src", "/lib/global/scripts/pt-add-ons/lightview-dialog.js");
			// FF
			dialog_js.onload = function(){
				(Lightview.start.bind(Lightview))();
			};
			// IE
			dialog_js.onreadystatechange = function() {
				if(dialog_js.readyState == "complete" || dialog_js.readyState == "loaded") {
					dialog_js.onreadystatechange = null;
					(Lightview.start.bind(Lightview))();
				}
			};
			head.appendChild(dialog_js);
		}
	},
*/
	initOptions: function() {
		dialog.options = {
				"autosize": true,
				"resizeDuration": 0.5
		};
	},

	show: function(newTitle, newMsg, options) {
		if(!newTitle || !newTitle.length || newTitle.length == 0) return;
		if(!newMsg || !newMsg.length || newMsg.length == 0) return;
/*		
		if(typeof(Lightview) == "undefined") { // Lets try again later...
			document.observe("lightview:loaded", function() {
				dialog.show(newTitle, newMsg, options);
			});
			dialog.init();
			return;
		}
*/
		if(!$('dialogBox')){
			dialog.init();
			dialog.show(newTitle, newMsg, options);
		}

		// Deal with any overrides
		var use_options = dialog.options;
		if(!!options) {
			// Copy everything over en mass
			//use_options.merge(options);
			for(var option in options) {
				switch(option) {
					case "autosize":
						// Native view option for Lightview
						use_options[option] = options[option];
					break;
					case "resizeDuration":
						// Static configuration option for Lightview
						Lightview.options.resizeDuration = options[option];
					break;
					case "onShow":
						if(typeof(options[option]) == "string")
							document.observe('lightview:opened', eval(options[option]));
						else
							document.observe('lightview:opened', options[option]);
					break;
					case "onHide":
						if(typeof(options[option]) == "string")
							document.observe('lightview:hidden', eval(options[option]));
						else
							document.observe('lightview:hidden', options[option]);
					break;
				}
			}
		}

		// Setup clean up function
		document.observe('lightview:hidden', function() {
			// Clear all callbacks
			document.stopObserving('lightview:opened');
			// Reset static options
			Lightview.options.resizeDuration = dialog.options["resizeDuration"];
		});
		if(!$('dialogBox')){
			dialog.init();
		}
		$('dialog-content').update(newMsg);
		//try {
			Lightview.show({
				title: newTitle,
				href: '#dialogBox',
				rel: 'inline',
				options: use_options
			});
		/*
		}
		catch (e) {
			// Oh well, alert it!
			alert(newMsg.stripTags());
		}
		*/
	},
	hide: function() {
		// AJAX login box
		if($("dialog")) $("dialog").hide();
		if(typeof(Lightview != "undefined")) Lightview.hide();
		if($("dialogBox")) $("dialogBox").hide();
	}
}

//Legacy Video SWF object stuff

if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;


var tabClass = Class.create({
	tabs: [],
	contentTabs: [],
	contentStruct: null,
	ajaxPath: null,
	initialize: function(targetNode) {
		this.targetNode = targetNode;
		this.setTabs();
	},
	setTabs: function() {
		var myClass = this;
		
		this.tabs = $A(this.targetNode.select('.tab'));
		this.ajaxPath = this.targetNode.id.replace(/_/gi, "/");
		this.tabs.each(function(tabAt) {
			Event.observe(tabAt, 'click', function() {
				myClass.changeTab(tabAt);
				goog.captureTabClick(tabAt);
			});
		});
		this.contentTabs = $A(this.targetNode.select('div.content'));
	},
	changeTab: function(obj) {
		this.tabs.each(function(tabAt) {
			tabAt.removeClassName('on');
		});
		obj.addClassName('on');
		var thisClass = this;
		this.contentTabs.each(function(contentAt,i) {
			if (thisClass.tabs.indexOf(obj) == thisClass.contentTabs.indexOf(contentAt)) {
				contentAt.addClassName('on');
				thisClass.checkContent(contentAt);
			} else {
				contentAt.removeClassName('on');
			}
		});
	},
	checkContent: function(cont) {
		var contentTarget = cont.select('div.content-target')[0];
		var thisClass = this;
		var nodeCap = 0;
//		if (sniff.isIE) { nodeCap = 0; }
		if (contentTarget.childNodes.length > nodeCap) { return; }
		if (!this.contentStruct) {
			new Ajax.Request('/ajax/get_tabs/' + thisClass.ajaxPath + '/', {
				method: 'get',
				onSuccess: function(t) {
					thisClass.contentStruct = $H(t.responseText.evalJSON()).toObject();
					thisClass.setContent(contentTarget);
				},
				onFailure: function(t) {
					
				}
			});
		} else {
			thisClass.setContent(contentTarget);
		}
	},
	setContent: function(obj) {
		var newContent = 'this.contentStruct.node_' + (this.contentTabs.indexOf(obj.parentNode) + 1);
		obj.update(eval(newContent));
	}
});

var vidEmbed = {
	
	playContent:function(vid,el,w,h,mode){
		var width = w;
		var height = h;
		var vidId = vid;
		var so = {};
		var target = el;
		var vidMode = mode;
		
		if(typeof(vidMode) == 'undefined'){vidMode = 'e';}
		
		if(!document.getElementById(target)){return false;}
		so = new SWFObject('/bin/vid-bin/jw/player-licensed.swf','player',width,height,'9');
		so.addParam('allowscriptacess', 'always');
		so.addParam('allowfullscreen', 'true');
		so.addParam('allownetworking', 'all');
		so.addParam('icons', 'false');
		so.addParam('wmode', 'opaque');
	  	so.addParam('flashvars','stretching=uniform&config=/svc/gpVid/'+ vidId + '/' + vidMode + '/');		
  	  	so.write(target);

	}
}

var hdrMenu = {
	initialItem: 'header',
	initialHeight: 0,
	secondaryItem: 'secondaryMenu',
	secondaryHeight: 0,
	initialStillShowing: true,
	init: function(){
		if(DetectTierTablet() || DetectTierIphone()){return false;}
		if(!$('secondaryMenu')){return false;}
		hdrMenu.initialHeight = $(hdrMenu.initialItem).getHeight();
		hdrMenu.secondaryHeight = $(hdrMenu.secondaryItem).getHeight();
		$(hdrMenu.secondaryItem).setStyle({visibility:'visible',top:-hdrMenu.secondaryHeight+'px'});
		hdrMenu.ifAtTop();
		Event.observe(window, "scroll", hdrMenu.ifAtTop);
		Event.observe(window, "resize", hdrMenu.ifAtTop);
		Event.observe(window, "unload", hdrMenu.removeListeners);
	},
	ifAtTop: function(){
		if( $(hdrMenu.initialItem).viewportOffset()[1] < -hdrMenu.initialHeight){
			hdrMenu.switchToSmall();
		} else if( $('header').viewportOffset()[1] >= -hdrMenu.initialHeight){
			hdrMenu.switchToLarge();
		}
	},
	switchToLarge: function(){
		hdrMenu.initialStillShowing = true;
		hdrMenu.cancelAnims();
		new Effect.Move($(hdrMenu.secondaryItem), { y: -hdrMenu.secondaryHeight, duration:.3, mode: 'absolute', queue: { position: 'end', scope: 'small' } });
	},
	switchToSmall: function(){
		hdrMenu.initialStillShowing = false;
		hdrMenu.cancelAnims();
		new Effect.Move($(hdrMenu.secondaryItem), { y: 0, duration:.3, mode: 'absolute', queue: { position: 'end', scope: 'small' } });
	},
	cancelAnims: function(){
		var queueSmall = Effect.Queues.get('small');
		queueSmall.each(function(effect) { effect.cancel(); });
	},
	removeListeners: function(){
		Event.stopObserving(window, "scroll", hdrMenu.ifAtTop);
		Event.stopObserving(window, "resize", hdrMenu.ifAtTop);
	}
}

var fbPrompt = {
	//check for FB link
	username: '',
	init: function(){
		var qStringVal = _tools.getQueryString("fbPrompt");
		if(qStringVal == "add"){
			fbPrompt.promptToAdd();
		}
		if(qStringVal == "preferences"){
			fbPrompt.promptPreferences();
		}
		//grab username
		if(!$$('.user-avatar a')[0]){
			return false;
		} else {
		fbPrompt.username=$$('.user-avatar a')[0].getAttribute('href').replace("/profile/view/","");
		}

	},
	promptToAdd: function(){
		fbPrompt.promptBox(
			'<span class="fbColor">Got  a Facebook account?</span><br/>Let\'s Get Associated!',
			'<p style="text-align:center;">GamePro has integrated Facebook Connect into the website.<br/><span style="color:#ffffff;">Share your comments, blogs, and user reviews easily<br/>with all your friends!</span></p>',
			'<button class="button" onclick="top.location=\'/profile/facebook/\'+fbPrompt.username" type="button">Set Preferences</button><button class="button" onclick="fbPrompt.closeBox();" type="button">No Thanks</button>'
		);
	},
	promptPreferences: function(){
		fbPrompt.promptBox(
			'<span class="fbColor">Facebook Sharing Preferences</span><br/>for your  GamePro account.',
			'<p style="text-align:center;">Please take a moment to let us know when and what to post to your Facebook account.  We tried mind-reading but it only works on albino chimps with three brains.</p>',
			'<button class="button" onclick="top.location=\'/profile/facebook/\'+fbPrompt.username" type="button">Set Preferences</button><button class="button" onclick="fbPrompt.closeBox();" type="button">No Thanks</button>'
		);
	},
	promptBox: function(title,text, buttons){
		//container
		var promptDiv = new Element('div',{'id': 'fbPromptBox'});
			//overlay
			var promptOverlay = new Element('div',{'class': 'fbOverlay'});
			//dialogBox
			var promptDialog = new Element('div',{'id': 'fbDialog'});
				//title
				var promptTitle = new Element('div',{'id': 'fbTitle'}).update(title);
				//text
				var promptText = new Element('div',{'id': 'fbText'}).update(text);
				//buttons
				var promptButtons = new Element('div',{'id': 'fbButtons'}).update(buttons);

		document.body.insert({top: promptDiv});
		$('fbPromptBox').insert(promptOverlay);
		$('fbPromptBox').insert(promptDialog);
		$('fbDialog').insert(promptTitle);
		$('fbDialog').insert(promptText);
		$('fbDialog').insert(promptButtons);
		
		$('fbPromptBox').setStyle({'display':'none'}).appear();
		$$('.fbOverlay')[0].observe('click',fbPrompt.closeBox);
	},
	closeBox: function(){
		$('fbPromptBox').fade();
		$$('#fbPromptBox .fbOverlay')[0].stopObserving('click',fbPrompt.closeBox);
	}
}

var socialToolBox = {
	//box on left of site for social interactions
	init: function(){
		if(DetectTierTablet() || DetectTierIphone()){return false;}
		//createBox
		socialToolBox.createBox();
	},
	createBox: function(){
//console.log('social box loaded');
		var socialTB = new Element('div',{'id': 'socialTB'});
			var socialCont = new Element('div',{'class':'socialCont','style':'position:relative'});
			var openItBox = new Element('div',{'id': 'openItBox'});
			var socialCloseBox = new Element('div',{'id': 'socialCloseBox'}).update('&laquo;');
			var socialButtonsBox = new Element('div',{'id': 'socialButtonsBox'});

				var stumbleUponLink = new Element('a',{'class': 'stb_stumbleUpon','href':'http://www.stumbleupon.com/to/stumble/stumblethru:gamepro.com?utm_source=GamePro&utm_medium=StumbleThru&utm_campaign=StumbleThruButton'}).update('Stumble thru GamePro');
				var facebookLink = new Element('a',{'class': 'stb_facebook','href':'http://www.facebook.com/gamepro/'}).update('Follow us on FaceBook');
				var twitterLink = new Element('a',{'class': 'stb_twitter aptureNoEnhance','href':'http://www.twitter.com/gamepro/'}).update('Follow Us on Twitter');

		document.body.insert({bottom: socialTB});
		socialTB.insert(socialCont);
		socialCont.insert(openItBox);
		socialCont.insert(socialButtonsBox);
		socialButtonsBox.insert(socialCloseBox);
		socialButtonsBox.insert(stumbleUponLink);
		socialButtonsBox.insert(facebookLink);
		socialButtonsBox.insert(twitterLink);
		socialToolBox.addTips();
		if(Cookie.get("isHidden") != "true"){
			//animate in if cookie says it's not hidden
			setTimeout(function(){
				socialToolBox.openBox();
			},1000);
		}
		//create closebox event listener
		Event.observe($('socialCloseBox'),'click', socialToolBox.closeBox);
		Event.observe($('openItBox'),'click', socialToolBox.openBox);
		Event.observe(window, "resize", socialToolBox.checkWidth);
		socialToolBox.checkWidth();
	},
	closeBox: function(){
//console.log("closing");
		Effect.Queues.get('socialBoxAnim').invoke('cancel');
		new Effect.Morph('socialButtonsBox',{
			style: 'left:-40px;',
			duration: .2,
			transition: Effect.Transitions.sinoidal,
			queue: { position: 'end', scope: 'socialBoxAnim' },
			afterFinish: function(){
				Cookie.set("isHidden","true",100000,'.gamepro.com');
			}
		});
	},
	openBox: function(){
//console.log("opening");
		Effect.Queues.get('socialBoxAnim').invoke('cancel');
		new Effect.Morph('socialButtonsBox',{
			style: 'left:0px;',
			duration: .5,
			transition: Effect.Transitions.spring,
			queue: { position: 'end', scope: 'socialBoxAnim' },
			afterFinish: function(){
				Cookie.set("isHidden","false",100000,'.gamepro.com');
			}
		});
	},
	checkWidth: function(){
//console.log(document.viewport.getWidth());
		if(document.viewport.getWidth() >= 1007){
			if($('socialTB').getStyle('display') != "block")
			$('socialTB').setStyle({display:'block'});
		} else {
			if($('socialTB').getStyle('display') != "none")
			$('socialTB').setStyle({display:'none'});
		}
	},
	checkDrag: function(){
		//allows for module to be moved up or down further on page
		//TO DO
	},
	addTips: function(){
		new Tip($$('.stb_stumbleUpon')[0],'Stumble thru GamePro.com', {
			style: 'gpcolors',
			stem: 'leftMiddle',
			offset: { x: 16, y: -16 },
			width: 'auto'
		});
		new Tip($$('.stb_facebook')[0],'Join us on Facebook', {
			style: 'gpcolors',
			stem: 'leftMiddle',
			offset: { x: 16, y: -16 },
			width: 'auto'
		});
		new Tip($$('.stb_twitter')[0],'Follow us on Twitter', {
			style: 'gpcolors',
			stem: 'leftMiddle',
			offset: { x: 16, y: -16 },
			width: 'auto'
		});
	}
}

document.observe('dom:loaded',util.init);
document.observe('dom:loaded',hdrMenu.init);
document.observe('dom:loaded',fbPrompt.init);
document.observe('dom:loaded',socialToolBox.init);
