$(document).ready(function() {

	updateHighScores = function ( scroll, keyword, tab, runOnce, gameMode, timeframe, specificDate ) {
		if ( typeof keyword != undefined ) {
			if ( tab == "mine" ) {
				$("#podHighScores > ul").tabs().tabs("select", 0);
				loadHighScoresTab( keyword, tab, runOnce );
			} else if ( tab == "overall" ) {
				$("#podHighScores > ul").tabs("select", 2);
				loadHighScoresTab( keyword, tab, runOnce, gameMode, timeframe, specificDate );
			}
		}
		if ( scroll ) {
			$.scrollTo('#podHighScores',500, { offset:-20 });
		}
	}

	// Function for tabbing around and AJAX loading within the High Scores Pod
	loadHighScoresTab = function ( keyword, tab, runOnce, gameMode, timeframe, specificDate ) {
		if ( runOnce ) {
			$( "." + tab + "Tab" ).removeAttr( "onclick" );
		}
		if ( gameMode == undefined || gameMode == null ) {
			gameMode = $("#" + tab + "GameMode :selected").val();

			// if the game mode hasn't been drawn yet, grab it from the 'mine' tab
			if ( gameMode == null ) {
				gameMode = $("#mineGameMode option:first").val();
			}
		}

		// try to populate the specificDate if it was not specified and a timeframe wasn't passed in
		if ( (specificDate == undefined) && (timeframe == undefined || timeframe == null) ) {
			specificDate = $("#" + tab + "DailyTimeframe option:selected").val();
			timeframe = null;
		}

		// if the specificDate is still null and a timeframe wasn't selected, then try to find the already selected timeframe
		if ( specificDate == null && timeframe == null) {
			timeframe = $("#" + tab + "Timeframe span.selected").html();

			// if the timeframe is STILL null (and since specificDate is as this point as well), default timeframe to ALLTIME
			if ( timeframe == null ) {
				timeframe = "ALLTIME";
			}
		}
		var url = "/services/highScore.jsp?h=" + tab + "&k=" + keyword + "&gm=" + gameMode + "&t=" + timeframe + "&d=" + specificDate;
		//alert( "posting:\n" + url );
		ajaxLoad( url, $("#podHighScores ." + tab + "HighScoreTab") );
	}

	//-----------------------------------------------------------------------
	// Javascript functions for handling review and rating submisssions
	// Handles user star rating submission.  Assumes that reviewForm is also on the page so the keyword is available.
	gameReviews_submitStarRating = function ( rating )
	{
		// Rating must be supplied to continue
		if ( !rating || rating == null || rating <= 0 )
		{
			return;
		}

		// Submit an AJAX post to the controller handling rating submissions
		$.post( "/member/submitRating.jsp",
			{
				rating: rating,
				gameKeyword: $("#reviewFormGameKeyword").val()
			},
			function ( data, textStatus ) {
				// do nothing
			}
		);
	}

	// Global var holding the current value of the user's star rating in the review form
	var reviewFormRating = 0;

	gameReviews_setReviewFormRating = function ( rating )
	{
		reviewFormRating = rating;
	}

	// show the submit button on the review form
	gameReviews_revertSubmitBtnState = function ()
	{
		$("#reviewFormProcessingButton").hide();
		$("#reviewFormSubmitButton").show();
	}

	// Handles the submission of the review form
	gameReviews_submitReviewForm = function ()
	{
		// hides submit review button
		$("#reviewFormProcessingButton").show();
		$("#reviewFormSubmitButton").hide();

		// hide form errors
		$("#reviewFormRatingError").hide();
		$("#reviewFormReviewError").hide();

		// Get the form fields
		var reviewText = $("#reviewFormReviewText").val();

		// Build up a string of error messages if params not supplied
		var errorMsgs = 0;

		if ( reviewText == null || reviewText == '' )
		{
			errorMsgs = 1;
			$("#reviewFormReviewError").show();
		}

		if( reviewFormRating == 0 )
		{
			errorMsgs = 1;
			$("#reviewFormRatingError").show();
		}

		// If there are errors, revert the submit button and return
		if ( errorMsgs > 0 )
		{
			gameReviews_revertSubmitBtnState();
			return;
		}

		var j=1;
		var tagVals = new Array(3);
		var tags = $( ".tagPick3 :checked" ).each( function ()
		{
			tagVals[ j ] = this.value;
			j++;
		});

		// Hide the review form.  We don't expect anything back from the AJAX post.
		gameReviews_showPostSubmissionDiv();

		// Submit an AJAX post to the controller handling review submissions
		$.post( "/member/writeReview.jsp",
			{
				reviewText: reviewText,
				rating: reviewFormRating,
				gameKeyword: $("#reviewFormGameKeyword").val(),
				tag1: tagVals[1],
				tag2: tagVals[2],
				tag3: tagVals[3]
			},
			function ( data, textStatus ) {
				// do nothing
			}
		);
	}

	gameReviews_showPostSubmissionDiv = function ()
	{
		$( "#reviewsWriteReviewForm" ).hide();
		$( "#reviewsSubmitComplete" ).show();
	}

	// Handle the user rating a review helpful/not-helpful
	gameReviews_rateReview = function ( reviewId, reviewHelpful )
	{
		 // Toggle the Report Helpful Review divs
		var userSubmissionLinkDivId = "#gameReviewReportHelpful-" + reviewId;
		$( userSubmissionLinkDivId ).html( 'Thank you for your submission.');

		// Submit an AJAX post to the controller handling review submissions
		$.post( "/member/reportHelpfulReview.jsp",
			{
				reviewId: reviewId,
				reviewHelpful: reviewHelpful
			},
			function ( data, textStatus ) {
				// do nothing
			}
		);
	}

	// Handle the user reporting that this is an abusive review
	gameReviews_reportAbusiveReview = function ( reviewId )
	{

		// Toggle the Report Abuse divs
		var userSubmissionLinkDivId = "#gameReviewReportAbuse-" + reviewId;
		var userSubmissionLinkDivSubmittedDivId = "#gameReviewReportAbuseSubmitted-" + reviewId;
		$( userSubmissionLinkDivId ).hide();
		$( userSubmissionLinkDivSubmittedDivId ).show();

		// Submit an AJAX post to the controller handling review submissions
		$.post( "/member/reportAbusiveReview.jsp",
			{
				reviewId: reviewId
			},
			function ( data, textStatus ) {
				// do nothing
			}
		);
	}

	// Make an AJAX call to FavoriteGamesAjaxController to add or delete a favorite
	// action param: valid values are 'add' or 'delete'
	gameReviews_updateFavoriteGames = function ( gameKeyword, action )
	{
		$.post( "/member/updateFavoriteGames.jsp",
			{
				keyword: gameKeyword,
				action: action
			},
			function ( data, textStatus ) {
				// do nothing
			}
		);
	}

	gameReviews_gameDrawerUpdateFavoriteGames = function ( trigger, gameKeyword, action )
	{
		// remove the parent element for the game
		$(trigger).parents("li:eq(0)").remove();

		gameReviews_updateFavoriteGames( gameKeyword, action );
	}

	gameReviews_gameLandingUpdateFavoriteGames = function ( gameKeyword, action )
	{
		$( "#addToFavoritesSpan" ).html( '<span class="icon16Lft icon16FavoriteAdded">Added to your Favorites</span>' );

		gameReviews_updateFavoriteGames( gameKeyword, action );
	}

	/**
	 * Function to launch the jigsaw player in the daughter window.
	 * day, month and year are optional parameters - if not specified, today's game will load
	 * @param keyword the game keyword
	 * @param isBonus whether or not the game is a bonus game
	 * @param day
	 * @param month
	 * @param year
	 */
	launchJigsaw = function( keyword, isBonus, day, month, year, width, height ) {
		var jigsawUrl = "/contentPlay/shockwave.jsp?dwin=1&id=" + keyword;
		var resizable = "no";
		if ( day && month && year ) {
			jigsawUrl = jigsawUrl + "&year=" + year + "&month=" + month + "&day=" + day;
		}
		if ( isBonus ) {
			jigsawUrl = jigsawUrl + "&bonus=bonus";
		}
		if ( keyword == 'jigsawpuzzlechallenge' || signedInState == 'SignedInPremium' || signedInState == 'SignedInClub' || signedInState == 'SignedInFreeClub' ) {
			resizable = "yes";
			jigsawUrl = jigsawUrl + "&fullScreen=1";
		}
		
		if (width) {
			launchWindow( jigsawUrl, width, height, resizable );
		} else {
			launchWindow( jigsawUrl, 775, 720, resizable );
		}
		
		
	}

	showLobbyGame = function() {
		$("#clubGameLobby").toggle();
		$("#gameHolder").toggle();
	}

	/**
	 * This function does 2 things:
	 * - loads in the progress on trophies with a simple JSON from the server
	 * - loads in 'WON' badges from a cookie on the filesystem
	 * @param gameKeyword the keyword of the game to load trophy progress and badges for
	 */
	loadTrophyProgress = function ( trigger, gameKeyword ) {

		// hide the trigger
		if ( trigger != null ) {
			$( trigger ).toggle().parent().next().toggle();
		}

		$.post('/myShockwave/trophyProgress.jsp?keyword=' + gameKeyword, {},
			function ( data, textStatus ) {

				// Expecting a JSON response back
				var progress = eval( '(' + data + ')' );
				for ( trophy in progress ) {
					var progressString = "";
					for ( progressItem in progress[ trophy ] ) {
						progressString += progress[ trophy ][ progressItem ];
					}
					$( "#" + trophy + " p.progress" ).html( progressString );
				}

				// restore the trigger
				if ( trigger != null ) {
					$( trigger ).toggle().parent().next().toggle();
				}
				return false;
			}
		);
		loadTrophyWonBadges();
	}

	loadTrophyWonBadges = function() {
		if ( $.cookie( 'trophies_won' ) ) {
			var trophiesWon = $.cookie( 'trophies_won' ).split(",");
			for ( var t in trophiesWon ) {
				var trophyWon = trophiesWon[t];
				$( "#" + trophyWon ).append("<div class='wonBadgeLrg'></div>");
			}
		}
	}

	var bingoPattern = "Reg";  // default starting pattern
	loadBingoLobbies = function ( tab, speed, pattern ) {
		var loadLobbyUrl = "/gamelanding/beachtowelbingo.jsp?speed=" + speed;
		if ( typeof pattern != "undefined" ) {
			bingoPattern = pattern;
			loadLobbyUrl += "&patternTab=true"
		}
		loadLobbyUrl += "&pattern=" + bingoPattern;
		var patternIndex = ( bingoPattern == "Reg" ) ? 0 : 1;
		ajaxTabLoad ( tab,
				loadLobbyUrl,
				false,
				function(){
					if ( typeof pattern == "undefined" ) {
						$('.bingoTypeTabs > ul').tabs().tabs('select', patternIndex );
					}
				}
		);
	}

	var pokerStake = "all";  // default starting stake
	var pokerStakeIndexes = {
		F :			0,
		100 :		1,
		1000 :		2,
		10000 :		3,
		100000 :	4,
		all:		5
	}

	loadPokerLobbies = function ( tab, roomType, stake ) {

		// ensuring IE targets the correct tab by grabbing anything after the '#' in the tab name only
		tab = tab.toString();
		tab = tab.substring( tab.indexOf("#"), tab.toString().length );

		// set the lobby url
		var loadLobbyUrl = "/gamelanding/texaspoker.jsp?roomType=" + roomType;
		if ( typeof stake != "undefined" ) {
			pokerStake = stake;
			loadLobbyUrl += "&stakeSet=true"
		}
		loadLobbyUrl += "&stake=" + pokerStake;
		ajaxTabLoad( tab,
				loadLobbyUrl,
				false,
				function() {
					$("#pokerStakes li.active").removeClass("active");
					$("#pokerStakes li.stake_" + pokerStake).addClass("active");
					//alert( pokerStakeIndexes[pokerStake] );
					//if ( typeof stake == "undefined" ) {
					//	$('.setStake > ul').tabs().tabs('select', pokerStakeIndexes[pokerStake] );
					//}
				}
		);
	}
	pokerQuickStart = function ( roomType ) {
		document.location.href = $("#pokerLobbies-" + roomType + " .quickStartLink").val();
	}

	// CHAT functions
	chat_showChatApp = function( chatObject ) {
		$( "#podChatEntry" ).hide();
		$( "#podChat" ).show();
		$( "#podChat" ).html( chatObject );
	}

	chat_closeChatApp = function() {
		$( "#podChat" ).hide();
		$( "#podChatEntry" ).show();
		$( "#podChat" ).html( '' );
	}

	// Launch a new window to the supplied screenname's profile page
	showChatUserProfile = function( screenname ) {
		window.open( '/member/profiles/' + screenname + '.jsp' );
	}

	showChatAbuseForm = function( reporterScreenname, abuserScreenname, chatTranscript, chatRoomId ) {
		document.reportAbuseForm.reporterScreenname.value = reporterScreenname;
		document.reportAbuseForm.chatTranscript.value = chatTranscript;
		document.reportAbuseForm.chatRoomId.value = chatRoomId;
		window.open( '/help/reportAbuse.jsp?chat=1&s=' + abuserScreenname );
	}

});