//load home page items on page load
$(document).ready(function() {
	new com.ag.TopGames().init();
	new com.ag.RecentReviews().populateReviews();
	$(".ag-tab-container").tabs({selected:0});
	new com.ag.RecentPlayedFavorites().init();
	new com.ag.NewVGGames().init();


	/*
		Builds and inserts the html for the trays.
	*/
	buildCarousel = function( context ) {
		if ( $.browser.msie && $.browser.version == "7.0" ) {
			$("#featured-games").css("left", 0); // ye olde ie7 css hack
		}

		for ( var i=0; i < context.trays.length; i++ ) { // for all the trays
			var key = context.returnIndex(i);
			var trayEl = '<div id="tray'+i+'" style="float: left; width: 0px;">';
			for ( var n=0; n < context.trays[i][key]["games"].length; n++ ) { // for each game in the tray
				if ( n < 3 ) { // max of 3 games per tray
					var game = context.trays[i][key]["games"][n]; // stub the object to make all the lookups below more legible
					var bombSpan = "";
					var isNewSpan = "";
					if ( game["hasBomb"] === true ) {
						bombSpan = ' <span class="bombSmall hideTxt">Mature Content</span>';
					}

					if ( game["isNew"] === true ) {
						if ($.browser.msie && $.browser.version == "7.0") {
							isNewSpan = '<div class="carouselIsNewIe7">NEW TODAY!</div>';
						} else {
							isNewSpan = '<div class="carouselIsNew">NEW TODAY!</div>';
						}
					}

					var picon = game["picon"];
					var idLength = picon.lastIndexOf( '.' ) - ( picon.lastIndexOf('/') + 1 );
					var classVal = 'fimage gameId-' + picon.substr( picon.lastIndexOf('/') + 1, idLength );

					var piconEl = '<a href="'+ game["target"] +'"><img src="'+ game["picon"] +'" class="'+ classVal +'" height="50" width="50" alt="" /></a>';

					trayEl += '<div class="featuredGame"><div class="fimageContainer">'+ piconEl +'</div><p><a href="'+ game["target"] +'">' + game["title"] + '</a><br />'+ game["description"] + bombSpan + '</p>'+ isNewSpan + '</div>';
				}
			}
			trayEl += "</div>";
			context.trayElements.push( trayEl );
		}
		$("#featuredGamesScroll").append( context.trayElements[0] );
		$("#featuredGamesScroll > div:first").css( "width", "auto" );
		$("#featuredGamesScroll").css( "width", context.trayWidth * context.trays.length ); // enables 'scrolling'
	};

	var carouselConfig = {
		leftScrollButton: '#featuredGamesLeftScroll',
		leftScrollCSSOff: 'featuredGamesLeftScrollOff',
		rightScrollButton: '#featuredGamesRightScroll',
		rightScrollCSSOff: 'featuredGamesRightScrollOff',
		headlineTextEl: '#trayText',
		scrollingEl: '#featuredGamesScroll',
		containingEl: "#featured-games",
		navEl: '#featuredGamesNav',
		navElCSSOn: "featuredGamesDotOn",
		buildCarouselFunction: buildCarousel,
		sortTray: true,
		events: {
			navClick: function( id ) { sendLinkEvent("featureCarouselDot" + id); },
			scrollLeft: function() { sendLinkEvent( "featureCarouselPrev" ); },
			scrollRight: function() { sendLinkEvent( "featureCarouselNext" ); }
		}
	};

	var FeaturedCarousel = new com.ag.Carousel( trays, trayRotationInterval, 534, carouselConfig );

});

/**
 * Creates an instance of TopGames
 * @constructor
 */
com.ag.TopGames = function() {

	this.domCache = new Array();
	this.ajaxFail = false;

	/**
	 * Entry point for TopGames
	 * @this {TopGames}
	 */
	this.init = function() {
		//this.populateTopGames();
		//this.attachTabEvents();
		//this.attachFilterEvent();

		// the tab and filter events are generated after the HTML is loaded from JSP
		this.loadMainFragment();
	};

	this.loadMainFragment = function() {

		var periodChannel = this.getTopGameSettings();

		if (!periodChannel.period) periodChannel.period = 'week';
		if (!periodChannel.channel) periodChannel.channel = 'homePage';


		var parentObject = this;
		$.ajax({
			url: "/home-frag/top-games.jsp",
			data: "period=" + periodChannel.period + "&channel=" + periodChannel.channel,
			success: function( data ) {
				$(".topGamesContainer").html(data);

				parentObject.removeTabEvents();
				parentObject.attachTabEvents();
				parentObject.attachFilterEvent();
			},
			error: function() {

			},
			dataType: "html"
		});
	}

	/**
	 * Determines if there is a cached version of the dom (based on period & channel) or not (will create) then
	 * appends dom fragment to the page
	 */
	this.populateTopGames = function() {
		var periodChannel = this.getTopGameSettings();
		var domToPopulate = '';
		var foundDom = false;

		if(this.domCache.length > 0) {
			for(var i=0; i<this.domCache.length; i++) {
				if (this.domCache[i].period == periodChannel.period && this.domCache[i].channel == periodChannel.channel) {
					domToPopulate = $(this.domCache[i].topGameDom);
					foundDom = true;
				}
			}
		}
		//check ajaxfail to make sure not infinitely recursive
		if (!foundDom) {
			if (this.ajaxFail == false) {
				this.createTopGamesDom();
			}
		} else {
			//empty in case it's not first time through
			$('.topGamesContainer .topGames').html( domToPopulate );
		}
	};

	/**
	 * Grabs JSON, iterates over the results, and populates the DOM w/ top games
	 * @this {TopGames}
	 */
	this.createTopGamesDom = function() {
		var parentObj = this;
		var createDom = '';
		var periodChannel = this.getTopGameSettings();
		if ( !periodChannel.period ) {
			periodChannel.period = 'week';
		}
		if ( !periodChannel.channel ) {
			periodChannel.channel = 'homePage';
		}

		//count = x -- server truncates # of responses
		//comment = false turns off dojo comment filtering of json response
		//var JSONURL = '/json/whatshot/plays?count=9&comment=false&period='+periodChannel.period+'&channel='+periodChannel.channel;
		var FRAGURL = "/home-frag/top-games/" + periodChannel.period + "/" + periodChannel.channel + ".jsp";

		$.ajax({
			url: FRAGURL,
			success: function( data ) {
				var createDom = data;
				if (jQuery.trim(createDom) == '') parentObj.ajaxFail = true;
				parentObj.domCache.push({'period':periodChannel.period, 'channel':periodChannel.channel, 'topGameDom':createDom});
				$('.topGamesContainer .topGames').html(data);
			},
			error: function() {
				parentObj.ajaxFail = true;
			},
			dataType: "html"
		});

	};

	this.removeTabEvents = function() {
		
		var periods = {'alltime':null, 'month':null, 'week':null};
		for ( period in periods ) {
			var selector = ".topGamesTabs > ." + period;
			$( selector ).unbind( 'click' );
		}
	}

	/**
	 * Attaches the click events to the top games tabs (time periods)
	 * @this {TopGames}
	 */
	this.attachTabEvents = function( period ){
		var context = this;

		var periods = {'alltime':null, 'month':null, 'week':null};

		delete periods[ context.getTopGameSettings().period ]; // remove selected tab, so we don't don't attach a click handler to it

		for ( period in periods ) {
			var selector = ".topGamesTabs > ." + period;
			context.attachSingleTabEvent( context, selector, period ); // attach handlers to the other two tabs
		}

		var selected = ".topGamesTabs > ." + context.getTopGameSettings().period;
		$( selected ).addClass( 'selected' );
	};

	this.attachSingleTabEvent = function ( context, el, period ) {
		$( el ).click( function() {
			var previouslySelectedTab = ".topGamesTabs > ." + context.getTopGameSettings().period; // the previously selected tab
			$( previouslySelectedTab ).removeClass( 'selected' ); // remove selected style

			context.setTopGameSettings( {'period':period, 'channel':context.getTopGameSettings().channel} );
			context.populateTopGames();
			$( el ).addClass( 'selected' );
			$( el ).unbind( 'click' );

			// reattach handler to previously selected tab
			context.attachSingleTabEvent( context, previouslySelectedTab, previouslySelectedTab.substr( previouslySelectedTab.lastIndexOf('.') + 1 ) );
		});
	};


	/**
	 * Attaches change event to the filter drop-down
	 * @this {TopGames}
	 */
	this.attachFilterEvent = function() {
		var parentObj = this;

		$.each($('#topGamesFilterSelect option'), function(i, option){
			if($(option).attr('value') == parentObj.getTopGameSettings().channel) $(option).attr('selected', 'selected');
		});
		$('#topGamesFilterSelect').bind('change', function(event){
			parentObj.removeTabEvents();
			parentObj.attachTabEvents();
			parentObj.setTopGameSettings({'period':parentObj.getTopGameSettings().period, 'channel':$('#topGamesFilterSelect option:selected').attr('value')});
			parentObj.populateTopGames();
		});
	};

	/**
	 * Retrieves the top games settings from the 'agTopGames' cookie
	 * @return {object} contains 'period' and 'channel' keys
	 * @see setTopGameSettings
	 */
	this.getTopGameSettings = function() {
		var cookieString = $.cookie('agTopGames');
		var returnVal;
		if (!cookieString) {
			this.setTopGameSettings();
			returnVal = this.getTopGameSettings();
		} else {
			returnVal = JSON.parse(cookieString);
		}
		return returnVal;
	};

	/**
	 * Persists the top games settings (filter and time period tab) in a 'agTopGames' cookie
	 * @param {object} settingsToPersist contains 'period' and 'channel' keys
	 * @see getPersistTopGameSettings
	 */
	this.setTopGameSettings = function(settingsToPersist) {
		if (typeof settingsToPersist == 'undefined') {
			var settingsToPersist = {};
		}
		if (!settingsToPersist.period) settingsToPersist.period = 'week';
		if (!settingsToPersist.channel) settingsToPersist.channel = 0;
		$.cookie('agTopGames', JSON.stringify(settingsToPersist));
	}
};

com.ag.RecentReviews = function() {
	this.populateReviews = function() {
		var JSONURL = '/json/recentReviews/frontPage?page=1&comment=false';

		$.ajax({url: JSONURL, dataType:'json', success: function(data) {
			$.each(data.reviews, function(i, review) {
				var output = $('<div class="recentReview clearfix"></div>');
				output.append('<div class="fimageContainer"><a href="/'+review.url+'"><img src="/fimages/'+review.gameId+'.png" alt="" class="fimage gameId-'+review.gameId+'"/></a></div>');
				var gameInfo = $('<div class="gameInfo"></div>');
				output.append(gameInfo);
				var titleBar = $('<div class="titleBar"></div>');

				if(review.rating == 'G') {
					titleBar.append('<div class="thumbUpDown" id="reviewThumbUp">&#160;</div>');
				} else {
					titleBar.append('<div class="thumbUpDown" id="reviewThumbDown">&#160;</div>');
				}
				titleBar.append('<h4 class="gameTitle"><a href="/'+review.url+'">'+review.name+'</a></h4>');
				titleBar.append('<a href="#" class="flagImg report">&#160;</a> <a href="#" class="report">Report</a>');
				$(titleBar).children('a.report').click(function(event){
					var report = new com.ag.ReportUserSubmittedContentAbuse();
					report.init({'itemId':review.reviewId,'typeCode':'Review','typeDesc':'review','reportLinkDom':$(this).parent().children('a.report')});
					event.preventDefault();
				});

				gameInfo.append(titleBar);

				gameInfo.append('<p class="gameReview">' + com.ag.showMoreLink(review.review, 120) + '</p>');

				gameInfo.append('<p><span class="lowlight">by</span> <a href="/profile/'+review.createdBy.profilePath+'">'+review.createdBy.username+'</a></p>');
				$('#moreReviews').before($(output));
			});
			}
		});
	};
};



com.ag.NewVGGames = function() {
	this.init = function() {

		var parentObject = this;
		$.ajax({
			url: "/home-frag/vg-games.jsp",
			success: function( data ) {
				$("#newVGGames").html(data);

				$(".newVGGame").each( function() {
					var context = $(this);
					context.find("a").click( function( e ) {
						e.preventDefault();
						var id = $(this).attr("id");
						var eventTitle = null;
						if ( $(this).hasClass("vgItem") ) {
							eventTitle = "ag_hppod_vgpicon_" + context.find(".localKeyword").text();
						} else {
							eventTitle = "ag_hppod_" + context.find(".localKeyword").text();
						}
						sendLinkEvent( eventTitle );
						window.location = $(this).attr("href");
					});
				});

				$("#vgHubLink").click( function( e ) {
					e.preventDefault();
					sendLinkEvent("ag_hppod_moreupgrades");
					var defer = function( ) {
						window.location = "/vg/index.php";
					}
					setTimeout( defer, 200 );
				} );
			},
			error: function() {
				$("#newVGGames").remove();
				$("#VGGamesBottomCurve").remove();
			},
			dataType: "html"
		});
	};
};

/**
 * Creates instance of the Recently Played/Favorites widget
 * @constructor
 */
com.ag.RecentPlayedFavorites = function() {
	/**
	 * Sets up the widget, figures out what needs to be populated, listens for login
	 */
	this.init = function() {
		var parentObject = this;
		AgEvent.LOGIN.subscribeOnce(bindContext(this, this.populateFavoritesTab));
		AgEvent.REGISTER.subscribeOnce(bindContext(this, this.populateFavoritesTab));
		AgEvent.LOGOUT.subscribeOnce(bindContext(this, this.unPopulateFavoritesTab));


		$('.ag-tab-container').bind('tabsselect', function(event, ui) {
			if($(ui.panel).attr('id') == 'tabRecentPlayed' && $('#tabRecentPlayed').children('.recentPlayedContainer').length <= 0){
				parentObject.populateRecentPlayedTab();
			}
		});

		if (LoginModule.getSessionUserUuid()) {
			this.populateFavoritesTab();
		} else {
			this.unPopulateFavoritesTab();
		}
	};
	/**
	 * Places user's favorites into the favorites tab
	 * @see unPopulateFavoritesTab
	 */
	this.populateFavoritesTab = function() {
		var parentObj = this;
		$('#tabFavorite').empty();
		var uuid = LoginModule.getSessionUserUuid();
		var requestObj = {"params":[{"types":["favorites"],"limit":6,"uuid":uuid}],"method":"favorites.get","id":1};
		$.post('/dynamic/services', JSON.stringify(requestObj), function(data) {
			if(data.result && data.result.favorites && data.result.favorites.length > 0) {
				$('#tabFavorite').empty();
				$.each(data.result.favorites, function(index, fave){
					var dom = $('<div class="favoriteContainer">'+
									'   <div class="faveDelete">&#160;</div>'+
									'   <a href="'+fave.url+'"><img src="/fimages/'+fave.id+'.png" class="fimage gameId-'+fave.id+'"/></a><br/>'+
									'   <a href="'+fave.url+'">'+fave.title+'</a>'+
									'</div>');
					$(dom).find('.faveDelete').click(function(event){
						var postData = {"params":[{"gameId":fave.id,"uuid":uuid}],"method":"favorites.remove","id":1};
						$.post('/dynamic/services', JSON.stringify(postData), function(data){
							parentObj.populateFavoritesTab();
						});
					});
					$('#tabFavorite').append(dom);
				});
			} else {
				parentObj.unPopulateFavoritesTab();
			}
		}, 'json');
	};

	/**
	 * Places generic content into the favorites tab
	 * @see populateFavoritesTab
	 */
	this.unPopulateFavoritesTab = function() {
		$('#tabFavorite').empty();
		$('#tabFavorite').append($('<img src="/static/images/favorites-call-to-action.png" alt="save your favorite games now with the favorite icon"/>'));
		if(!LoginModule.getSessionUserUuid()) {
			$('#tabFavorite').append($('<img src="/static/images/login-now.png" id="favoritesTabLoginBtn" alt="login now"/>'));
			$('#favoritesTabLoginBtn').click(function(event){
				LoginModule.showLogin();
			});
		}
	};

	/**
	 * Places the user's most recently played games (max 6) in the just played tab
	 */
	this.populateRecentPlayedTab = function() {
		var cookieString = $.cookie('agRecentlyPlayed');
		if(cookieString) {
			var gameArray = cookieString.split(',');
			gameArray.reverse();
			for (var i in gameArray) {
				var JSONURL = '/static/frag/games/layover/'+gameArray[i].substr(3)+'/'+gameArray[i]+'.js';
				$.ajax({url: JSONURL, dataType:'json', dataFilter:function(data,type) {
					//remove comment filtering
					if(data.substring(0,2) == '/*') data = data.substring(2, data.length - 2);
					return data;

				}, success: function(data){
					var dom = $('<div class="recentPlayedContainer">'+
									'   <a href="/'+data.url+'"><img src="/fimages/'+data.id+'.png" class="fimage gameId-'+data.id+'"/></a><br/>'+
									'   <a href="/'+data.url+'">'+data.title+'</a>'+
									'</div>');
					$('#tabRecentPlayed').append(dom);
				}});
			}
		} else {
			$('#tabRecentPlayed').empty();
			$('#tabRecentPlayed').append($('<p>The next time you play a game, it will be listed here for quick access.</p>'));
		}
	};
};
