/***************************
 * Embedded game page code. 
 * Handles 
 *   ad refreshing,
 *   pregame-game state changing,
 *   facebook connect,
 *   pregame-igp sign-in/sign-up and
 *   friends feed. *
 ***************************/

egp = {
	fbUserId : null,
	fbAppId : null,
	fbAccessToken : null,
	gameWidth : null,
	roomId : null,
	isGuest : null,
	connectUrl : null,
	showFriends : null,
	getConnectUrl : function(options) {
		var url = egp.connectUrl;
		if (url) {
			if (typeof(options) == 'object') {
				jQuery.each(options,function(key, value){
					if(url.indexOf('?')<0){
						url += '?'+(key+'='+value); 
					} else {
						url += '&'+(key+'='+value);
					}
				});
			}
		}
		return url;
	},
	//egpBindings.js implements these methods
	handleFacebookStatus : function(response){},
	showPregame : function(){},
	showPregameAd : function(){},
	showGame : function(){},
	toggleFriends : function(showFriends){}
};

(function($) {	
	var methods = {
		getGlobalVar : function(varName) {
			if ((typeof(GLOBAL_VARS) === 'object') && (typeof GLOBAL_VARS[varName] != 'undefined')) {
				return GLOBAL_VARS[varName];
			}
			return null;
		},
		setGlobalVar : function(varName,value) {
			GLOBAL_VARS[varName]=value;
		}
	}
	EGP_STATES = {
		PREGAME : 'pregame',
		GAME    : 'game' //may include _<roomid> for a specific room
	};
	/**********************
	 * Ad reloading code  *
	 **********************/
	var egpAds = {
		intervalID : null,
		//function to refresh the ads on the page
		refresh : function(){
			adSeed = new Date().getTime();
			$('.refreshableAd').each(function(i, el){
				el = $(el);
				adSrc = el.attr('refreshSrc') + "&adSeed="+adSeed; 
				el.html('<iframe src="'+adSrc+'" width="'+el.attr('frameWidth')+'" height="'+el.attr('frameHeight')+'" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" allowtransparency="true">Your browser does not support iframes.</iframe>');
			});
		},
		hide : function(){
			$('.hideableAd').hide();
		},
		show : function(){
			$('.hideableAd').show();
		},
		//function to change the ad targets (calls egpAds.refresh as well)
		switchToGameAds : function(){
			if(egp.gameWidth>820){
				//hide sky scrapper
			}
			egpAds.refresh();
			if($('.refreshableAd').length>0 && !egpAds.intervalID){
				//Set up the 5 min ad refresh
				egpAds.intervalID = window.setInterval(function(){
					egpAds.refresh();
				}, 5*60*1000);
				//Set up a way to refresh the ads manually for testing.
				$('.refreshAds').click(function(){
					egpAds.refresh();
				});
			}
		}
	}
	
	
	/***********************
	 * State machine code  *
	 ***********************/
	var egpStateMachine = {
		hashChange : function() {
			var hash = location.hash.replace(/^#/, '');
			if ((hash.length >= 4)
					&& (hash.substring(0,EGP_STATES.GAME.length) == EGP_STATES.GAME)) {
				// figure out the connection url
				if (hash.length >= 5) {
					egp.roomId = hash.substring(5);
				} else {
					egp.roomId = null;
				} 
				// hide pregame div and show game
				$('#embeddedGame').show();
				$('#embeddedGameOverview').hide();
				if(methods.getGlobalVar("GAME_WIDTH")>790){
					$('#clubSidebar').hide();
				}
				if(methods.getGlobalVar("GAME_WIDTH")>820){
					$('#middle.middle').addClass('wide');
					$('#skyscrapper-ad').hide();
					$('#skyscrapper-ad .refreshableAd').removeClass('refreshableAd');
				}
				if($(window).scrollTop()>$("#game-wrapper").offset().top){
					$('html, body').animate({
						scrollTop: $("#game-wrapper").offset().top
					}, 2000);
				}
				var id = egpStateMachine.timeout
				if(id){
					clearTimeout(id)
				}
				var adDelay = methods.getGlobalVar("AD_DELAY");
				if(adDelay>0 && !(methods.getGlobalVar("AD_DISABLED_FOR_VISITED_GUEST") && methods.getGlobalVar("VISITED_GUEST"))){
					methods.setGlobalVar('VISITED_GUEST',true);
					egpStateMachine.loadAd();
					egpStateMachine.timeout = setTimeout(egpStateMachine.loadGame,adDelay);
				} else {
					egpStateMachine.loadGame();
				}
			} else if (hash.length==0 || hash==EGP_STATES.PREGAME) {
				var id = egpStateMachine.timeout;
				if(id){ 
					clearTimeout(id)
				}
				egpAds.show();
				egp.showPregame();
			}
		},
		loadAd : function(){
			egp.showPregameAd();
			egpAds.hide();
		},
		loadGame : function(){
			egpStateMachine.timeout = null;
			egp.showGame();
			egpAds.switchToGameAds();
			egpAds.show();
		}
	};

	

	

	$(document).ready(function() {
		egp.fbUserId = methods.getGlobalVar('FB_USER_ID')
		egp.fbAppId = methods.getGlobalVar('FB_APP_ID');
		egp.connectUrl = methods.getGlobalVar('CONNECT_URL');
		egp.gameHeight = methods.getGlobalVar("GAME_HEIGHT");
		egp.gameWidth = methods.getGlobalVar("GAME_WIDTH");
		egp.isGuest = methods.getGlobalVar("IS_GUEST");
		egp.showFriends = methods.getGlobalVar("SHOW_FRIENDS");
		if(egp.showFriends!='false'){
			egp.showFriends = true;
		}
		
		$('.egpFriendsToggle').click(function(){
			if(egp.showFriends){
				$.ajax({url:'/game/egp/preferences.do?var=viewFriends&val=false'});
				$(this).addClass('hiddenFriends');
				egp.showFriends = false;
				egp.toggleFriends(false);
				$('.egpFriendsToggle span').replaceWith('<span>Show Friends</span>');
			} else {
				$.ajax({url:'/game/egp/preferences.do?var=viewFriends&val=true'});
				$(this).removeClass('hiddenFriends');
				egp.showFriends = true;
				egp.toggleFriends(true);
				$('.egpFriendsToggle span').replaceWith('<span>Hide Friends</span>');
			}
		})
		
		$('#challengeTemplate').setupChallengeFeed();
		
		// set up the hash change monitor
		$(window).hashchange(egpStateMachine.hashChange);
		
		$('a.addFriendAlertBox').popup();
		egpStateMachine.hashChange();
		
		comparePlaying = function(f1,f2){
			function isPlaying(f,gameCode){
				return typeof(f.playing)!='undefined' && typeof(f.playing.code)!='undefined' && f.playing.code==gameCode;
			}
			var pageCode = methods.getGlobalVar("GAME_CODE");
			if(isPlaying(f1,pageCode) && !isPlaying(f2,pageCode)){
				return -1;
			}
			if(!isPlaying(f1,pageCode) && isPlaying(f2,pageCode)){
				return 1;
			}
			return 0;
		}
		comparePlayed = function(f1,f2){
			var code = methods.getGlobalVar("GAME_CODE");
			t1 = t2 = 4294967295;
			if(f1.played && f1.played[code]){
				t1 = f1.played[code];
			}
			if(f2.played && f2.played[code]){
				t2 = f2.played[code];
			}
			if(t1<t2){
				return -1;
			}
			if(t1>t2){
				return 1;
			}
			return 0;
		}
		$(document).bind('friendAdded',function(){
			$('#friendsTemplate').processFeed({
				'preprocessFeed':function(feed){
					feed.friends = feed.friends.sort(function(f1,f2){
						diff = comparePlaying(f1,f2);
						if(diff!=0){
							return diff;
						}
						diff = comparePlayed(f1,f2);
						if(diff!=0){
							return diff;
						}
						if(f1.userId<f2.userId){
							return 1;
						}
						if(f1.userId>f2.userId){
							return -1;
						}
						return 0;
					});
					if(feed.friends.length>3){
						feed.friends.length = 3;
					}
					while(feed.friends.length<3){
						feed.friends.push(1);
					}
				},
				'postLoad':function(){
					$('a.addFriendAlertBox').popup();
				}
			});
		});
		$(document).trigger('friendAdded');
		
		
		//init facebook
		if($('#fb-root').length==0){
			$('body').append($('<div id="fb-root"></div>'));
		}
		FB.init({appId: PogoFBConstants.apiKey, status: true, cookie: true, xfbml: true});
		FB.Event.subscribe('edge.create', function(response) {
			//if they liked the page they are logged in. Get status
			FB.getLoginStatus(function(response) {}, {});
		});
		FB.Event.subscribe('auth.statusChange', egp.handleFacebookStatus);
		FB.getLoginStatus(egp.handleFacebookStatus, {});
		
		//set up the sign up popups using the igp popup
		if($('#igpDiv').length>0){
			var domain = $('#igpDiv').attr('domain');
			var generalCookiePrefix = $('#igpDiv').attr('generalCookiePrefix');
			var gameCode = $('#igpDiv').attr('game');
			if(!domain || !generalCookiePrefix || !gameCode){
				pogoLog("whoa! igp div is missing domain, generalCookiePrefix or gameCode. Please fix or reg and signin links won't work");
			}
			var options = {
				width: 900,
				height : 400,
				domain : domain,
				generalCookiePrefix : generalCookiePrefix,
				gameCode : gameCode,
				preGameRedirect : true,
				authenticationLevel : 'guest'
			};
			if(typeof OLD_IE_VERSION_NO_IGP == 'undefined'){
				$(".registerLink").live('click',function(event){
					options.initPanel='signUp';
					var pageSection = $(event.target).attr('pageSection');
					options.pageSection = pageSection;
					igpHelper = $('#igpDiv').pogoIGPHelper({},options, $().pogoUserMgr());
					return false;
				});
				$(".signinLink").live('click',function(event){
					options.initPanel='signIn';
					var pageSection = $(event.target).attr('pageSection');
					options.pageSection = pageSection;
					igpHelper = $('#igpDiv').pogoIGPHelper({},options, $().pogoUserMgr());
					return false;
				});
			}
		}
		//set up the favorite buttons
		$(".favoriteButton").favoriteButton();
	});
})(jQuery);

