$(document).ready(function() 
{
	//Handler for language dropdown
	$('#country-select').change(function()
	{
		window.location = $(this).val();
	});

	//---------- Site-wide Hover State ----------//
	
	//Set all hover-effect anchor tags to be the width and height
	//of their parents minus 6px for the border. Saves tedious CSS.
	$('a.hover-effect').each(function()
	{
		width = $(this).parent().width();
		height = $(this).parent().height();

		$(this).width(width - 6);
		$(this).height(height - 6);
	});
	
	//---------- Game Tile Hover States ----------//
	
	//Adds appropriate hover states to all effected elements whenever
	//a game tile is hovered.
	$('div.game').hover(
	function()
	{
		$(this).find('a.hover-effect').addClass('hover');
		$(this).find('span.play-now').addClass('hover');
		$(this).find('h5').addClass('hover');
	},
	function()
	{
		$(this).find('a.hover-effect').removeClass('hover');
		$(this).find('span.play-now').removeClass('hover');
		$(this).find('h5').removeClass('hover');
	});
	
	//---------- Free Play Hover State ----------//
	
	//Set hover state for free play.
	$('span.free-play').hover(
	function()
	{
		$(this).addClass('hover');
	},
	function()
	{
		$(this).removeClass('hover');
	});
	
	//---------- Members Area Menu Hover ----------//
	
	//Toggles the my-account-menu list items so users can navigate
	//in fewer clicks
	$('#my-account-menu li').hover(
	function()
	{
		//Give 'active' appearance to hovered items but ignore
		//the actual active item.
		if( ! $(this).hasClass('active'))
		{
			//Highlight around button
			$(this).addClass('hover');
			//Highlight button itself
			$(this).children(":first").addClass('hover');
		}
		
		//Toggle the appropriate sub-menu
		$(this).parent().find('li.active ul').hide();
		$(this).find('ul').show();
	},
	function()
	{
		//Undo the hover state
		if( ! $(this).hasClass('active'))
		{
			$(this).removeClass('hover');
			$(this).children(":first").removeClass('hover');
		}
		
		//Reset the menu display.
		$(this).find('ul').hide();
		$(this).parent().find('li.active ul').show();
	});
});

//------------------------------------------------------------------------

/**
 *	init_ads_jps
 *
 *	Starts the hero ad and jackpot animations
 */
function init_ads_jps()
{
	//Start ads
	if(run_ads)
	{
		//Width of one image
		var imageWidth = $("#window").width();
		//Number of images
		var imageSum = $("div#ads img").size();
		//Total width of image area
		var adsWidth = imageWidth * imageSum;

		$('div#ads').width(adsWidth);
		$('div#ads img:first').addClass('active');
		
		//ad_interval is saved so we can stop the interval if needed.
		ad_interval = setInterval('update_ads()', 3000);
	}
	
	//start jps
	if(run_jps)
	{	
		//jp_interval is saved so we can stop the interval if needed.
		jp_interval = setInterval('update_jackpots()', 5000);
	}
}

//------------------------------------------------------------------------

/**
 *	update_ads
 *
 *	Animates the hero ad display.
 */
function update_ads()
{
	//How for has the div already moved?
	var left_offset = parseInt($('div#ads').css('left').replace('px', ''));
	
	//Whats the next animation increment?
	var img_width = $('div#ads img').width();
	
	//The new animation offset (from 0). Either 0 or a negative value
	var slide_distance = left_offset - img_width;
	
	//When the div has travelled it's width - 1 image width, we dont want to go any further
	var reset_width = $('div#ads').width() - img_width;

	//Make this value positive for comparison
	var distance_travelled = slide_distance * -1;
	
	//Animate.
	if(distance_travelled > reset_width)
	{
		$('div#ads').animate({left: 0}, 1000);
	}
	else
	{
		$('div#ads').animate({left: slide_distance}, 1000);
	}
}

//------------------------------------------------------------------------

/**
 *	update_jackpots
 *
 *	Loops continuously through all jackpot values
 */
function update_jackpots()
{
	//Grab the next jackpot item
	if($('ul#jackpots li.active').next().length > 0)
	{
		next = $('ul#jackpots li.active').next();
	}
	else
	{
		next = $('ul#jackpots li:first-child');
	}
	
	//Fade out the current jackpot item
	$('ul#jackpots li.active').fadeOut('slow', function() 
	{
		$(this).removeClass('active');
		
		//Fade in the next jackpot
		next.fadeIn('slow', function()
		{
			$(this).addClass('active');	
		});
	});
}

//------------------------------------------------------------------------

/**
 *	pop_dialog
 *
 *	Opens a modal dialog and centers it on screen.
 *
 *	url 	- The relative url to load into the dialog
 *	width	- The minimum width of the dialog
 *	height	- The minimum height of the dialog
 */
function pop_dialog(url, width, height)
{
	back_to_top();

	$('div#public.modal').modal(
	{
		minWidth: width,
		minHeight: height,
		onOpen: function(dialog)
		{
			//Animate the overlay
			dialog.overlay.slideDown('slow', function () 
			{
				//Make sure the contents of the dialog are showing
				dialog.data.show();
				
				//Preload
				$('div#public.modal div.dialog-preloader').show();
				$('div#public.modal img.logo').show();
				
				//Fade in preloader display and perform AJAX request
				dialog.container.fadeIn('fast', function()
				{
					data = ajax_page_load(url, false, false);

					//On success, show dialog contents
					if(data.statusText == 'OK')
					{
						$('div#public.modal div.container').hide();
						$('div#public.modal div.container').html(data.responseText);
						$('div#public.modal div.dialog-preloader').hide('blind', function()
						{
							$('div#public.modal div.container').show('blind');
						});
					}
				});
			});
		},
		onClose: function(dialog)
		{
			//Fade out the dialog
			dialog.container.fadeOut('slow', function()
			{
				//If we're closing the dialog, animate the overlay off.
				dialog.overlay.slideUp('slow', function()
				{
					//Clean up the mess.
					$.modal.close();
				});
			});
		}
	});
}

//------------------------------------------------------------------------

/**
 *	load_dialog
 *
 *	Loads new data into an already open dialog
 *
 *	url 	- The relative url to load into the dialog
 *	width	- The minimum width of the dialog
 *	height	- The minimum height of the dialog
 */
function load_dialog(url, width, height)
{
	//Hide the dialog
	$('#simplemodal-container').fadeOut('slow', function()
	{
		//Hide the dialog contents and show preloader
		$('div#public.modal div.container').hide()
		$('div#public.modal div.dialog-preloader').show();
	
		//Set the new width
		$('#simplemodal-container').width(width);
		$('#simplemodal-container').height(height);
		$.modal.setPosition();
		
		//Fade container back in with preload message
		$('#simplemodal-container').fadeIn('slow', function()
		{
			//Perform AJAX request to load new dialog
			data = ajax_page_load(url, false, false);
		
			//On success, show dialog contents
			if(data.statusText == 'OK')
			{
				$('div#public.modal div.container').html(data.responseText);
				$('div#public.modal div.dialog-preloader').hide('blind', function()
				{
					$('div#public.modal div.container').show('blind');
				});
			}
		});
	});
}

//------------------------------------------------------------------------

function submit_dialog_form(the_form)
{
	$('div#public.modal div.container').hide('blind', function()
	{
		$('#' + the_form).ajaxSubmit(
		{
			success: function(response)
			{
				$('div#public.modal div.container').html(response);
				
				$('div#public.modal div.container').show('blind');
			}
		});
	});
}

//------------------------------------------------------------------------

/**
 *	pop_members_area
 *
 *	Opens a modal dialog containing the deposit and my account functionality.
 *	This is almost exactly the same as pop_dialog except that it also loads
 *	a static menu and has static dimensions.
 *
 *	url - The relative url to load into the dialog
 */
function pop_members_area(url)
{
	back_to_top();

	$('div#account.modal').modal(
	{
		minWidth: 900,
		minHeight: 700,
		onOpen: function(dialog)
		{
			//Animate the overlay
			dialog.overlay.slideDown('slow', function () 
			{
				//Make sure the contents of the dialog are showing
				dialog.data.show();
				
				//Preload
				$('div#account.modal div.dialog-preloader').show();
				$('div#account.modal img.logo').show();
				
				//Fade in preloader display and perform AJAX request
				dialog.container.fadeIn('fast', function()
				{
					data = ajax_page_load(url, true, true);

					//On success, show dialog contents
					if(data.statusText == 'OK')
					{
						$('div#account.modal div.dialog-preloader').hide();
						$('div#account.modal div.container').html(data.responseText);
						$('div#account.modal div.container').show('blind');
						$('#my-account-menu').show();
						$('#my-account-submenu').show();
					}
				});
			});
		},
		onClose: function(dialog)
		{
			//Fade out the dialog
			dialog.container.fadeOut('slow', function()
			{
				//If we're closing the dialog, animate the overlay off.
				dialog.overlay.slideUp('slow', function()
				{
					//Clean up the mess.
					$.modal.close();
				});
			});
		}
	});
}

//------------------------------------------------------------------------

/**
 *	load_members_area
 *
 *	Loads a new page into the already opened members
 *	area dialog.
 *
 *	url - The relative url to load.
 */
function load_members_area(url)
{
	$('div#account.modal div.container').hide('blind', function()
	{
		data = ajax_page_load(url, true, true);
		
		if(data.statusText == 'OK')
		{
			$('div#account.modal div.container').html(data.responseText);
			$('div#account.modal div.container').show('blind');
		}
	});
}

//------------------------------------------------------------------------

/**
 *	submit_members_area
 *
 *	Performs an AJAX submit for forms inside of the members area dialog
 */
function submit_members_area()
{
	$('#input-form').hide();
	$('.in-dialog-preloader').show();
	
	$('#input-form').ajaxSubmit(
	{
		success: function(response)
		{
			$('div#account.modal div.container').html(response);
			$('div#account.modal div.container').show('blind');
		},
		error: function(jqXHR)
		{
			//If a user's session is expired the request will return a 401 status
			//We use that as an indication that we should redirect the user.
			if(jqXHR.status == '401')
			{
				window.location.href = webRoot + 'login/session_expired';
			}
		}
	});
}

//------------------------------------------------------------------------

function update_balance()
{
	$('div#balance ul').fadeOut('fast', function()
	{
		data = ajax_page_load('/members/update_balance', false, true);
		
		if(data.statusText == 'OK')
		{
			$('div#balance ul').html(data.responseText);
			$('div#balance ul').fadeIn('fast');
		}
	});
}

//------------------------------------------------------------------------

/**
 *	ajax_page_load
 *
 *	Performs an AJAX request for the given URL. Returns an
 *	XMLHttpRequest object.
 *
 *	url - The relative url to load.
 */
function ajax_page_load(url, update_nav, members_only)
{
	data = $.ajax(
	{
		dataType: 'html',
		url: webRoot + url,
		type: 'POST',
		async: false,
		beforeSend: function()
		{
			//Update the highlighted nav items
			if(update_nav)
			{
				ajax_nav_update(url);
			}
		},
		error: function(jqXHR)
		{
			//If a user's session is expired the request will return a 401 status
			//We use that as an indication that we should redirect the user.
			if(jqXHR.status == '401' && members_only == true)
			{
				window.location.href = webRoot + 'login/session_expired';
			}
		}
	});
	
	return data;
}

//------------------------------------------------------------------------

//Interval ID for game timer
var play_timer;

/**
 *	load_game
 *
 *	Loads a casino game.
 *
 *	the_form - The associated form required for launching a specific game.
 */
function load_game(the_form, game_type, game_style, free_play)
{
	//If this is free play then make sure we submit the free play game form
	if(free_play)
	{
		the_form = the_form + '_free';
	}

	//Launch the game
	$('#' + the_form).ajaxSubmit(
	{
		dataType: 'json',

		//Scroll the game into view
		beforeSend: function()
		{
			//Animate game list left
			$('#content-wrap').animate({left: $('#content-wrap').width()}, 1000);
		},
        success: function(response) 
		{   
			//Scroll the page back to the top
			$('html').animate({scrollTop:0}, 'slow', function()
			{
				//Cleanup aisle 3...
				$('#footer-top').fadeOut('slow');
				$('#content-wrap').hide();
				
				//Load the view
				$('#game-wrap').html(response.view_data);
				
				//Set game background
				var background_img = webRoot + 'common/images/games/' + game_type + '/' + game_style + '_lrg.jpg';
				$('#game-area').css('background-image', 'url(' + background_img + ')');
				
				//Set game width and height
				$('#game').width(response.game_data.width);
				$('#game').height(response.game_data.height);
				
				//Hide the navigation for free play
				if(free_play)
				{
					$('ul#main-nav li').fadeOut('fast');
					$('#forgot_password_link').hide();
				}
				
				//Stop updating ads and js values if they are currently running
				if(ad_interval)
				{
					clearInterval(ad_interval);
				}
				
				if(jp_interval)
				{
					clearInterval(jp_interval);
				}
				
				//Show the game
				$('#game-wrap').fadeIn('fast', function()
				{
					embed_movie(response.game_data);
					
					//Display and start the game timer for Danish players
					if(current_lang == 'da')
					{
						$('#game-timer').css('display', 'inline-block');
						play_timer = setInterval(update_timer, 1000);
					}
				});
			});
        },
		error: function(jqXHR)
		{
			//If a user's session is expired the request will return a 401 status
			//We use that as an indication that we should redirect the user.
			if(jqXHR.status == '401')
			{
				window.location.href = webRoot + 'login/session_expired';
			}
		}
    });
}

//------------------------------------------------------------------------

/**
 *	embed_movie
 *
 *	Uses swf object to embed a casino game.
 *
 *	game_data - A JSON object containing a URL to the movie clip as well 
 *				as the width and height of the movie clip.
 */
function embed_movie(game_data)
{
	var params = 
	{
		allowScriptAccess: 'always',
		bgcolor: '#B2B2B2',
		menu: 'false',
		scale: 'showall',
		wmode: 'transparent',
		base: game_data.base
	};
	
	swfobject.embedSWF(game_data.movie_url, "swf-embed", game_data.width, game_data.height, "9.0.0", "", "", params);
}

//------------------------------------------------------------------------

//Cumulative count of seconds since we started the game
var seconds_since_launch = 0;

/**
 *	update_timer()
 *
 *	Updates a play timer indicating the length of time a player has
 *	playing a specific game.
 */
function update_timer()
{
	//Reset the clock when it reaches 99:59:59.
	if(seconds_since_launch == 360000)
	{
		seconds_since_launch = 0;
	}
	
	var minutes = Math.floor(seconds_since_launch / 60);
	
	//Are we up to hours yet?
	if(minutes >= 60)
	{
		var hours = Math.floor(minutes / 60);
		
		//Determine the remaining minutes
		minutes = minutes  - hours * 60;
		
		//Format hours to two digits
		if(hours < 10)
		{
			hours = '0' + hours;
		}
	}
	//No? Default to '00'
	else
	{
		hours = '00';
	}
	
	//Format minutes to two digits
	if(minutes < 10)
	{
		minutes = '0' + minutes;
	}
	
	var seconds = seconds_since_launch % 60;
	
	//Format seconds to two digits
	if(seconds < 10)
	{
		seconds = '0' + seconds;
	}

	$('#game-timer').html(hours + ':' + minutes + ':' + seconds);
	
	seconds_since_launch++;
}

//------------------------------------------------------------------------

/**
 *	requestClose
 *
 *	Flash callback handler. Executed whenever the flash game client wants to close.
 */
function requestClose(reason)
{
	close_game();
}

//------------------------------------------------------------------------

/**
 *	close_game
 *
 *	Closes an open game and restores the content that was previously there.
 */
function close_game()
{
	$('#game-wrap').fadeOut('slow', function()
	{
		$('#game-wrap').html('');
		
		$('#content-wrap').show();
		
		$('#content-wrap').animate({left: 0}, 1000, function()
		{
			$('ul#main-nav li').fadeIn('slow');
			$('#footer-top').fadeIn('slow');
            if ($('#forgot_password_link').length)
            {
                $('#forgot_password_link').show();
            }
			
			//Restart ads and jps if necessary
			if(run_ads)
			{
				ad_interval = setInterval('update_ads()', 3000);
			}
			
			if(run_jps)
			{
				jp_interval = setInterval('update_jackpots()', 5000);
			}
			
			//Stop the play timer
			clearInterval(play_timer);
			//Reset the counter
			seconds_since_launch = 0;
		});
	});	
}

//------------------------------------------------------------------------

/**
 *	back_to_top
 *
 *	Scroll the page back to the top.
 */
function back_to_top()
{
	$('html, body').animate({scrollTop:0}, 'slow');
}
