
/**
 * Note that we have to use window.onload because $(document).ready() fires before images are loaded
 * and ul.innerWidth() - container.outerWidth(); doesn't give the correct width because the width
 * of the UL hasn't expanded out until the images have finished rendering.
 */
window.onload = function () {
    //getFilteredGames("most-popular", "popular");
};

$(document).ready(function(){
	/*
	Switch tabs and fetch the right data
	*/
	$("#scroll-tabs a").click(function(){
		// var id = this.hash.replace('#', '');
		var id = $(this).attr("name");
		//remove id="selected-tab"
		$("#scroll-tabs").find("#selected-tab").removeAttr("id");
		//add id="selected-tab" on clicked item
		$(this).parent().attr("id","selected-tab");				
		
		//remove subgames
		removeSubgame();
		if (id == "list-view-content"){
			$("#all-games-menu").css({"visibility":"hidden"});
			getFilteredGames("list-view", id);
		}else{
			if(id == "popular"){
				getFilteredGames("most-popular", id);
				$("#all-games-menu").css({"visibility":"hidden"});					
			}else{
				// getFilteredGames("all-games", id);
				getFilteredGames("all-games", "games");
				$("#all-games-menu").css({"visibility":"visible"});
				$("#all-games-menu").find("#selected-sub-menu").attr("id","");
				$("#all-games").parent().attr("id","selected-sub-menu");
			}
		}
		$(this).blur();
	});
	/*
	Get filtered games from sub menu
	*/
	$("#game-section > li > a").livequery('click', function(){
		//remove game popup if present
		removeSubgame();
		var gameType = $(this).attr('id');
		
		getFilteredGames(gameType, "games");
		
		//remove previous selected menu item
		$(this).parent().parent().find("#selected-sub-menu").attr("id","");
		
		//add selected id on this menu item
		$(this).parent().attr("id", "selected-sub-menu"); 			
		$(this).blur();
		return false;
	});
	// Get additional games
	$(".more-games").livequery('click', function(e){
		offsetX = 80;
		offsetY = 40;
		var posX = $(this).offset().left + offsetX;
		var posY = $(this).offset().top - offsetY;
		//var subgameId = e.currentTarget.id;
		var subgameId = $(this).attr("id");

		if($("#subgames").size() == 0)
		{				
			//get games through ajax-call?
			$.getJSON("/games/carousel/index.php", { method : 'subgame', id : subgameId }, function(json){
				$(json.html).appendTo("body");
				$("#subgames").css({ top : posY, left : posX }).show();
				$("#subgames a").nwPopup();
			});
		}else{
			removeSubgame();
			$.getJSON("/games/carousel/index.php", { method : 'subgame', id : subgameId }, function(json){
				$(json.html).appendTo("body");
				$("#subgames").css({ top : posY, left : posX }).show();
				$("#subgames a").nwPopup();
			});
		}			
		//remove border around a-tag onclick
		$(this).focus().blur();
		return false;
	});
	
	$(".rollover").hover(function(e) {
		var offsetY = 98;
		var offsetX = 20
		//var oContainer = "<span id='preview-image'></span>";
		// var id = this.id;
		var w = $("#" + this.id).height();
		var i = -100;
		var imageStart = w + "px";
		var img = this.id + ".jpg";
		var posX = (e.pageX + offsetX);
		var posY = (e.pageY - offsetY);
		var oContainer = "<span id='preview-image'><img src='ui/image/games/carousel/thumbs/" + img +"' /></span>";
		
		$("body").append(oContainer);
		$("#preview-image")
			.css({ position: "absolute", top : posY, left : posX, border : "1px solid #e5b837"})
			.fadeIn("fast");
	}, function(){
		$("#preview-image").remove();
	});
	$("#container, .handle").click(function(){
		removeSubgame();
	});
});

/*
Get Filtered Games
*/
function getFilteredGames(gameType, showTab){
	/*
		Hide all tabs, remove json added content and show the selected tab
	*/
	$("div#popular, div#games, div#list-view-content").hide();
	$("div#popular ul li, div#games ul li").remove();
	$("div#" + showTab).show();

	if(gameType == "list-view"){
		// var container = $('div.sliderGallery');
		var container = $('#list-view-content .sliderGallery');
        var divThatGetsCropped = $('ul', container);
        // var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth();

		//Scroll back to left position
		$('.slider', container).slider("moveTo",0);
		
		//Destroy all references to the slider (if it exists), otherwise it can behave odd
		$('.slider', container).slider("destroy");

        $('.slider', container).slider({
            min: 0,
            max: 900, //itemsWidth,
            handle: '.handle',
            stop: function (event, ui) {
                divThatGetsCropped.animate({'left' : ui.value * -1}, 500);
            },
            slide: function (event, ui) {
                divThatGetsCropped.css('left', ui.value * -1);
            }
        });
	
	}else{
		$("#loader").css('visibility', 'visible');
		$.getJSON("/games/carousel/index.php", { method: 'filteredGames', section : gameType }, function(json){
			$(json.html).appendTo("#" + showTab + " .sliderGallery ul");
			$("#" + showTab + " .sliderGallery ul a").nwPopup();

			var container = $('#' + showTab + ' .sliderGallery');
            var ul = $('ul', container);
			// var itemsWidth = (json.items * 151) + (json.items * 20);
			var responseWidth = (json.items > 16) ? Math.round((json.items * 151) * 1.204) : json.items * 151;

			//Scroll back to left position
			$('.slider', container).slider("moveTo",0)
			
			//Destroy all references to the slider, otherwise it can behave odd (if it exists)
			$('.slider', container).slider("destroy");

            $('.slider', container).slider({
                min: 0,
                max: responseWidth,
                handle: '.handle',
                stop: function (event, ui) {
                    ul.animate({'left' : ui.value * -1}, 500);
                },
                slide: function (event, ui) {
                    ul.css('left', ui.value * -1);
                }
			});	
			$("#loader").css('visibility', 'hidden');
		});	
	}		
}

/***************************
 Add click event to links
***************************/
$.fn.nwPopup = function() {
	return this.each(function(){
	    if(this.href.indexOf("/games/play/?clientcode=") != -1)
	    {
	    	if (this.onclick == null)
	        {
	        	//Parse client code and pass as second param
	            $(this).click(function()
				{
	                	popNWGameWindow(this.href, $.getParameter('clientcode', this.href), $.getParameter('width', this.href), $.getParameter('height', this.href));
	                    return false;
				});
			}
		}else if(this.href.indexOf("/games/play/?gamecode=") != -1){					
			//Parse client code and pass as second param
	        $(this).click(function(){
				popNEGameWindow( this.href, $.getParameter('gamecode', this.href) );
				return false;
			});
		}
	});	
}
/* Remove subgames */
function removeSubgame()
{
	$("#subgames").remove();
}
