var $_sCurrentContentDiv = '#numbers-search-numbers-contents';
var $_gtc;
var $_oGame;

var loadGame = function( $sGame, $bNumbers ) {
	var $gtc = null;

	if ( $sGame != '' ) {
		$.getJSON( '/social/getGameByName/json/57b734183ff751ba6d0a4e9f098fa762/' + $sGame, function($sData) {
			$_sCurrentContentDiv = '#numbers-search-numbers-contents';
			$('#SBN_game_id').val($sGame);
			$_gtc = $sData.getGameByNameResults.game.gameType;
			$_oGame = $sData.getGameByNameResults.game;

			//	Replace search header for sit and wins...
			if ( $sData && $sData.getGameByNameResults.game.gameType == 4 ) {
				$('h2#search-by-numbers').attr('id','search-by-draw');
				$('#numbers-search-draw-contents').empty().show();
			} else {
				$('h2#search-by-draw').attr('id','search-by-numbers');
				$('#numbers-search-numbers-contents').empty().show();
			}

			//	Load the search form for this game...
			$($_sCurrentContentDiv).load( '/social/getGameSearchForm/json/57b734183ff751ba6d0a4e9f098fa762/' + $sGame + '/0', function(){
				if ( $sData.getGameByNameResults.game.gameType == 4 ) {
					$('#frmSingleSearch input#search-type').remove()
					$('#frmSingleSearch').append('<input type="hidden" id="search-type" name="search-type" value="search-by-draw" />');
				} else {
					$('#frmSingleSearch input#search-type').remove()
					$('#frmSingleSearch').append('<input type="hidden" id="search-type" name="search-type" value="search-by-numbers" />');
				}

				//	Show search form if there is no data...
				if ( ! $_bHaveResults )
					$(this).show();

				//	Force numbers only and auto-tab
				$('form.numbers-search input.numeric').numeric().autotab_magic();

				//	Finally, show the search buttons
				$('input.game-search-button').removeAttr('disabled').show();
				$('#sbn-search-button').toggle((""!=$sGame));

				//	Show loading message while searching...
				$('#frmSearchDate,#frmSingleSearch').submit(function(e){
					var $_iCount = 0;
					var $_iTotal = 0;
					var $_sAll = '';
					var $_iFailCount = 0;
					var $_bFail = false;

					//	Make sure we have all the numbers first...
					if ($(this).attr('id')=='frmSingleSearch') {
						$(this).find('input.numeric').each(function(){
							$_iTotal++;
							if ( $(this).val() ){
								$_iCount++;
							}else{
								$(this).addClass('input-error');
							}
							$_sAll += $(this).val();
						});

						if ( $_bPartial && $_sAll == '' ) {
							$_bFail = true;
						} else if ( $_iCount != $_iTotal ) {
							$_bFail = true;
						}

						if ( $_bFail ) {
							e.preventDefault();
							alert($_gtc==4?'You must enter a draw number to search!':'You must enter all numbers to search.');
							return false;
						}

						//	Now check to make sure that each number is within range...
						$(this).find('input.numeric').each(function(){
							if ( $_oGame && ! $(this).hasClass('draw-number') && $(this).attr('id') != 'SBN_bonus_nbr' ){
								var $_iValue = parseInt($(this).val(),10);

								if ( isNaN($_iValue) || $_iValue < parseInt($_oGame.minimumValue,10) || $_iValue > parseInt($_oGame.maximumValue,10) ) {
									$(this).addClass('input-error');
									$_iFailCount++;
								}
							}
						});

						if ( $_iFailCount != 0 ) {
							alert('The numbers you entered must be from ' + $_oGame.minimumValue + ' to ' + $_oGame.maximumValue);
							return false;
						}

						if ( $_oGame.hasBonus == 1 && $('#SBN_bonus_nbr').length != 0 )
						{
							var $_iMin = parseInt($_oGame.bonusMinimumValue,10);
							var $_iMax = parseInt($_oGame.bonusMaximumValue,10);
							var $_iValue = parseInt($('#SBN_bonus_nbr').val(),10);

							if ( isNaN($_iValue) || $_iValue < $_iMin || $_iValue > $_iMax ) {
								$('#SBN_bonus_nbr').addClass('input-error');
								alert('Your ' + $_oGame.bonusBallName + ' entry must be between ' + $_iMin + ' and ' + $_iMax);
								return false;
							}
						}
					}

					if ( ! $_bFail )
					{
						$('form input.input-error').removeClass('input-error');
						$('input.game-search-button').attr('disabled','disabled');
						$('#interior-left').loading(true,{text:'Searching...',align:'center'});
					}
					return !$_bFail;
				});



				//	And some focus...
				$('#SBN_win_seq_1_nbr').focus();
			});
		});
	}

	return $gtc;
}

/**
* Document Ready
*/
$(function(){

	//	We have results, load up the game and show results
	if ( $_bHaveResults )
	{
		$('div#game-search-form').hide();
		loadGame( $_sCurrentGame );

		//	Click for details
		if ( $_iResultCount > 0 || $_bAllGames )
		{
			$('.game-search-results-row').click(function(e){
				e.preventDefault();
				if ( $_sUrl = $(this).attr('rel') )
					window.open( $_sUrl );
				return false;
			});
		}

		//	Previous/Next
		if ( ! $('a.previous, a.next').hasClass( 'disabled' ) ) {
			$('a.previous, a.next').click(function(e){
				$('#interior-left').loading(true,{text:'Searching...',align:'center'});
				return true;
			});
		}

		//	Bind search again link
		$('#game-search-again-trigger').click(function(e){
			e.preventDefault();
			$('#game-search-results').hide();
			$($_sCurrentContentDiv).show();
			$('#SBN_game_id').val($_sCurrentGame);
			$('#SDR_game_id').val($_sCurrentGame);
			$('div#game-search-form').fadeIn();
			return false;
		});
	}
	else
	{
		//	No results for you
		$('#game-search-results').hide();
		$('div#game-search-form').show();

		if ( $_sPreloadGame != '' )
		{
			var $_sGame = $_sPreloadGame.replace(/-/g,'_');
			$('select#SDS_game_id,select#SBN_game_id,select#SBD_game_id,select#SDR_game_id').val($_sGame);
			$($_sCurrentContentDiv).show();
			loadGame($_sGame);
		}
	}

	//	Bindings
	if ( $_iResultCount > 0 || $_bAllGames ) {
		if (  ! $_bTiered ) {
			//	Download
			$('#game-search-download').click(function(e){
				e.preventDefault();
				var $_oWin = window.open('/numbers/home/exportCsv', 'winCsv', 'status=0,toolbar=0,menubar=0,resizable=0,resizeable=0,width=500,height=220');
				$('#frmCsv').attr('target', 'winCsv').submit();
				return false;
			}).css('color','#777').attr('title','');
		}
		else
			$('a#game-search-download').css({color:'#ccc','text-decoration':'none','cursor':'default'}).attr('title','Results download is not available for this result set');

		//	Print
		$('#game-search-print').click(function(e){
			e.preventDefault();
			var $_oWin = window.open('/numbers/home/printSearch', 'winPrint');
			$('#frmPrint').attr('target', 'winPrint').submit();
			return false;
		}).css('color','#777').attr('title','');
	}
	else
	{
		//	Turn off download/print if no results
		$('a#game-search-download').css({color:'#ccc','text-decoration':'none','cursor':'default'}).attr('title','Results download is not available for this result set');
		$('a#game-search-print').css({color:'#ccc','text-decoration':'none','cursor':'default'}).attr('title','Printing is not available for this result set');
	}

	//	SBN game change
	$('#SBN_game_id').change(function(e){
		$('input#sbn-search-button').hide();
		$('div#numbers-search-numbers-contents').empty();
		loadGame($(this).val(),true);
		return true;
	});

	//	Advanced search jump
	$('#date-search-advanced-search-text').click(function(e){
		e.preventDefault();
		window.location.hash = 'numbers-search-advanced-wrapper';
		return false;
	});

	$('#frmSearchAdvanced').submit(function(e){
		if ( $('#frmSearchAdvanced #SDR_game_id').val() == '' ){
			alert( 'Please choose a game to search!' );
			return false;
		}
		return true;
	});

	$('#sdmy-game-search').click(function(e){
		e.preventDefault();
		$('#frmSearchAdvanced')
			.remove('#search-type')
			.append('<input type="hidden" id="search-type" name="search-type" value="search-date-month-year" />')
			.submit();

		return false;
	});

	$('#sdr-game-search').click(function(e){
		e.preventDefault();
		$('#frmSearchAdvanced')
			.remove('#search-type')
			.append('<input type="hidden" id="search-type" name="search-type" value="search-date-range" />')
			.submit();
		return false;
	});

	//	Cool button hoveres
	$('input.game-search-button')
		.hover(
			function() {
				$(this).attr('src', '/images/site/search-button-hover.png' );
			},
			function() {
				$(this).attr('src', '/images/site/search-button.png' );
			}
		);


});
