var browseGame = '';
var gamesHeight = '';
var viewPage = 1;
var games = new Array();
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();

function bindGames() {
	$('.screenshot_filter div').each(function() {
		$(this).click(function() {
		
			window.viewPage = 1;
		
			$('#screenshot_container').empty();
			//window.browseGame = $(this).attr('action');
		
			if($(this).attr('action') != 'all') {
				$(this).hide();
				$('div[action|="all"]').after(this);
				$(this).fadeIn();
				$.history.load('!/'+$(this).attr('action'));
			} else {
				window.browseGame = '';
				$.history.load('');
			}
			$('.screenshot_filter').addClass('menuhidden');
			highlightActiveGame();
		});
	});
}

function highlightActiveGame() {
	$('.screenshot_filter div').removeClass('active');
	if (window.browseGame == '') {
		$('div[action|="all"]').addClass('active');
		document.title = 'MMO Screenshots @ scrnTAG';
	} else {
		if(window.browseGame != 'all') {
			$('div[action|="all"]').after($('div[action|="'+window.browseGame+'"]').addClass('active'));
			document.title = $('.screenshot_filter > div[action|="'+window.browseGame+'"]').html() + ' @ scrnTAG';
		}
	}
}

function displayGames(games) {
	$('.screenshot_filter:visible').slideUp();
	$('.screenshot_filter').html('').append('<div action="all">All Games</div>');
	$.each(games, function() {
		window.games.push(this.Game.shortname);
		$('.screenshot_filter').append('<div action="'+this.Game.shortname+'">'+this.Game.name+'</div>');
	});
	$('.screenshot_filter').append('<span class="clear"></span>');
	$('.screenshot_filter').slideDown();
	
	bindGames();
	highlightActiveGame();
}

function loadScreenshots(game) {
	// Screenshot loading function
	// Checks global space for active game, how many we're currently displaying
	// Also checks filter for user

	// Do some stuff
	console.log('Loading screenshots for: '+game);
	$.getJSON('/screenshots/fetch/game:'+game+'/page:'+window.viewPage, function(json) {
		displayScreenshots(json);
	});
}

function displayScreenshots(screenshots) {
	var first = true;
	$.each(screenshots, function() {
		if(first == true) {
			displayShot = '<div class="grid_4"><div class="screenshot_cont" action="'+this.Screenshot.id+'" image="/i/298/222/298:222/'+this.Screenshot.image+'"><div class="screenshot"><div class="hover"><div><div class="title">'+this.Screenshot.title+'</div><div class="game">'+this.Game.shortname+'</div></div><div class="user">by <span>'+this.User.username+'</div></div></div></div></div>';
			first = false;
		} else {
			displayShot = '<div class="grid_2"><div class="screenshot_cont" action="'+this.Screenshot.id+'" image="/i/138/100/138:100/'+this.Screenshot.image+'"><div class="screenshot"></div></div></div>';
		}
		
		$('#screenshot_container').append(displayShot);
		
	});	
	
	loadImages();
}

function loadImages() {
	backgrounder = new Array();
	bgimage = new Array();
	container = new Array();
	
	$('.screenshot_cont').not('.loaded').each(function(index) {		
		if($(this).is(':in-viewport')) {
			container[index] = $(this);
			bgimage[index] = $(this).attr('image');
			backgrounder[index] = $('.screenshot', this)
			
			var img = $("<img />").css('display', 'none').attr('src', bgimage[index])
				.load(function() {
					backgrounder[index].css('background-image', 'url('+bgimage[index]+')').fadeIn();
					container[index].addClass('loaded');
				});
				
			$(this).click(function() {
				$.history.load('!/'+window.browseGame+'/'+$(this).attr('action'));
				//viewScreenshot($(this).attr("action"));
			});
		}
	});
}

function resetViewer() {
	$('.screenshot_tone').hide();
	$('.screenshot_viewer').hide();
	$('.screenshot_viewer').width(window.viewportWidth-120);
	$('.screenshot_viewer').height(window.viewportHeight-120);
}

function viewScreenshot(screenshot) {
	console.log('Screenshot viewer called');
	// Reset the container
	resetViewer();
	
	// Fetch the screenshot details
	$.getJSON('/screenshots/single/'+screenshot, function(json) {
		
		var vH = $('.screenshot_viewer').height();
		var vW = $('.screenshot_viewer').width();
	
		console.log(json);
		
		console.log('Comparing ' + json.Screenshot.height + ' with ' + vH);
		if(json.Screenshot.height < vH) {
			console.log('Returning viewer height is larger.');
			console.log('Resizing...');
			$('.screenshot_viewer').animate({
				height: json.Screenshot.height
			}, 1000);
		}
		
		console.log('Comparing ' + json.Screenshot.width + ' with ' + vW);
		if(json.Screenshot.width < vW) {
			console.log('Returning viewer width is larger.');
			console.log('Resizing...');
			$('.screenshot_viewer').animate({
				width: json.Screenshot.width
			}, 1000);
		}
		
		// Fetch the image and set it as the background of the container
		var bg = '/i/'+vW+'/'+vH+'/'+vW+':'+vH+'/'+json.Screenshot.image;
		console.log(bg);
		var img = $("<img />").css('display', 'none').attr('src', bg)
			.load(function() {
				$('.screenshot_viewer').css('background-image', 'url('+bg+')');
		});
		
	});
	
	// Adjust the size of the container appropriately 
	// Fetch the correctly sized screenshot
	$('.screenshot_tone').fadeIn();
	$('.screenshot_viewer').fadeIn();
}

$(document).ready(function() {

	$('.screenshot_tone').hide();
	$('.screenshot_viewer').hide();

	$.getJSON('/games/fetch', function(json) { 
		displayGames(json);
	});
	
	$('.screenshot_filter').addClass('menuhidden');
	$('.screenshot_filter').hover(
		function () {
			$(this).removeClass('menuhidden');
		},
		function () {
			$(this).addClass('menuhidden');
		}
	);
	
	$('.footer_contents').hide();
	
	$('.footer_button').mouseover(
		function() {
			$('.footer_contents:hidden').slideDown();
		}
	);
	
	$('.footer').mouseleave(
		function() {
			$('.footer_contents:visible').slideUp();
		}
	);
	
	$('.screenshot_tone').click(
		function() {
			$.history.load('!/'+window.browseGame);
		}
	);
	

	$.history.init(function(url) {
		if(/^!\//.test(url)) {
			url = url.substring(2);
			url = url.split("/");			
			console.log(url);

			if(url[0] !== undefined) {
				console.log('Game is defined as: '+url[0]);
				console.log('Global is defined as: '+window.browseGame);
				// Check if this is a game	
				console.log('Looking for: '+url[0]+' in the following array...');
				console.log(window.games);
				
				/*
				if($.inArray(url[0], window.games) > -1) {
					console.log('Game has been found.');
				*/				
					if(url[0] != window.browseGame) {
						$('#screenshot_container').hide().empty().fadeIn();
						window.browseGame = url[0];
						console.log('Global is defined as: '+window.browseGame);
						loadScreenshots(window.browseGame);
						highlightActiveGame();
				
					}
				/*
				} else {
					// Not a game, might be a user
					console.log(url[0]+' was not found in the array.');
					// User checking elements here
				}
				*/
			}
		
			if(url[1] !== undefined) {
				// Second item should always be a screenshot ID
				if(!isNaN(parseFloat(url[1]))) {
					// Load the screenshot
					console.log('Screenshot ID defined as: '+url[1]);
					viewScreenshot(url[1])
				} else {
					console.log(url[1]+' is not a number, so not a screenshot ID.');
				}
			} else {
				$('.screenshot_tone').hide();
				$('.screenshot_viewer').hide();
			}
			
		} else {		
			$('#screenshot_container').hide().empty().fadeIn();
			$.getJSON('/screenshots/fetch', function(json) {
				displayScreenshots(json);
			});
		}
	},
	{ unescape: ",/!"});
});

$(window).scroll(function() {
	console.log('Scroll top: '+ $(window).scrollTop() + '  Doc height: ' +$(document).height()+ ' Window height: ' +$(window).height());
	if($(window).scrollTop() >= ($(document).height()-200)- $(window).height()) {
		console.log('Loading more now...');
		window.viewPage = parseInt(window.viewPage) + 1;
		loadScreenshots(window.browseGame);
	}
	
	loadImages();
});

$(window).resize(function() {
	window.viewportWidth = $(window).width();
	window.viewportHeight = $(window).height();
});
