jQuery(function() 
{
    /***** ITEM BLOCKS *****/

	jQuery('.item-block-load-more-options > span').mouseover(function() 
	{
		jQuery(this).parent().prev().html('&#10012; Load ' + jQuery(this).html().replace('+','') + ' more');
		jQuery('#' + jQuery(this).parent().parent().parent().attr('id') + '-numberposts').val(jQuery(this).html().replace('+',''));
	});

	jQuery('.item-block-load-more-options > span').mouseout(function() 
	{
		var parent = jQuery(this).parent().parent().parent();
		jQuery(this).parent().prev().html('&#10012; Load ' + jQuery('#' + jQuery(this).parent().parent().parent().attr('id') + '-numberposts_default').val() + ' more');
		jQuery('#' + jQuery(this).parent().parent().parent().attr('id') + '-numberposts').val(jQuery('#' + jQuery(this).parent().parent().parent().attr('id') + '-numberposts_default').val());
	});
	
	jQuery.fn.loadItemBlock = function() 
	/* use on ".item-block-body" element to load and append more items */
	{
		var block = this;
		var parent = block.parent();
		var loadmore = block.next();

		var type = jQuery('#' + parent.attr('id') + '-type').val();
		var relation = jQuery('#' + parent.attr('id') + '-relation').val();
		var related = jQuery('#' + parent.attr('id') + '-related').val();
		var display = jQuery('#' + parent.attr('id') + '-display').val();
		var category = jQuery('#' + parent.attr('id') + '-category').val();
		var tag = jQuery('#' + parent.attr('id') + '-tag').val();
		var offset = jQuery('#' + parent.attr('id') + '-offset').val();
		var numberposts = jQuery('#' + parent.attr('id') + '-numberposts').val();
		var filtertype = jQuery('#' + parent.attr('id') + '-filtertype').val();
		var filtervalue = jQuery('#' + parent.attr('id') + '-filtervalue').val();
		var langfilter = jQuery('#' + parent.attr('id') + '-langfilter').val();
		var group = jQuery('#' + parent.attr('id') + '-group').val();
		var ajaxinit = jQuery('#' + parent.attr('id') + '-ajaxinit').val();

		var new_offset = parseInt(offset) + parseInt(numberposts);
		jQuery('#' + parent.attr('id') + '-offset').val(new_offset);

		loadmore.toggleClass('loading');
		
		jQuery.ajax({
		  url: "http://www.planet3ds.net/api/",
		  data: "ajax=1&relation=" + relation + "&related=" + related + "&offset=" + offset + "&numberposts=" + numberposts + "&type=" + type + "&display=" + display + "&category=" + category + "&tagged=" + tag + "&filtertype=" + filtertype + "&filtervalue=" + filtervalue + "&langfilter=" + langfilter + "&group=" + group,
		  success: function(data) 
		  {
			block.append("<div style=\"display:none\">" + data + "</div>");
			block.children(":last").slideDown();
			loadmore.toggleClass("loading");

			/*Remove block if Ajax Init failed*/
			if((data == '')&&(ajaxinit == 1)) parent.remove();

			if(exceeded == 1)
			{
				loadmore.hide();
				exceeded = 0;
			}
		  }
		});
	}
	
	jQuery(".item-block-filters > .refresh").click(function() 
	{
		/* (Re)set offset to 0 */
		jQuery('#' + jQuery(this).parent().parent().attr('id') + '-offset').val('0');
		/* Delete block items */
		jQuery(this).parent().next().html('');
		/* Show "load more" button */
		jQuery(this).parent().parent().find('.item-block-load-more').show();
		/* Refresh */
		jQuery(this).parent().next().loadItemBlock();
	});
	
	jQuery(".item-block-filters > select").change(function() 
	{
		if(jQuery(this).hasClass('langfilter'))
		{
			/* Set block's langfilter value */
			jQuery('#' + jQuery(this).parent().parent().attr('id') + '-langfilter').val(jQuery(this).attr('value'));
		}
		else if(jQuery(this).hasClass('group'))
		{
			/* Set block's langfilter value */
			jQuery('#' + jQuery(this).parent().parent().attr('id') + '-group').val(jQuery(this).attr('value'));
		}
		else
		{
			/* Set block's filter values */
			jQuery('#' + jQuery(this).parent().parent().attr('id') + '-filtertype').val(jQuery(this).attr('name'));
			jQuery('#' + jQuery(this).parent().parent().attr('id') + '-filtervalue').val(jQuery(this).val());
		}

		/* (Re)set offset to 0 */
		jQuery('#' + jQuery(this).parent().parent().attr('id') + '-offset').val('0');
		/* Delete block items */
		jQuery(this).parent().next().html('');
		/* Show "load more" button */
		jQuery(this).parent().parent().find('.item-block-load-more').show();
		/* reload (filtered) items */
		jQuery(this).parent().next().loadItemBlock();
	});

	jQuery("a.item-block-head").hover
	(
		function() //onmouseover
		{
			jQuery(this).find('.full').html(jQuery(this).attr('title'));
		},
		function() //onmouseout 
		{
			jQuery(this).find('.full').html(jQuery(this).find('input').val());
		}
	);
    
    
	
	//Automatic smooth scrolling
	jQuery(function()
	{
		jQuery('a[href*=#]').click(function() 
		{
			if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
				&& location.hostname == this.hostname) 
			{
				var $target = jQuery(this.hash);
				$target = $target.length && $target || jQuery('[name=' + this.hash.slice(1) +']');
				if ($target.length) 
				{
					var targetOffset = $target.offset().top;
					jQuery('html,body').animate({scrollTop: targetOffset-10}, 500);
					return false;
				}
			}
		});
	});

	jQuery.fn.loadTab = function() 
	{
		//Change CSS to make tab active
		jQuery(".tabs > a").removeClass("active");
		jQuery(this).addClass("active");

		//Load content
		var url = '?ajax=1&t=' +  jQuery(this).attr("href").replace("#/","").replace("/","");
		jQuery('.main-content-body').html('<div class=\'games-list-refreshing\'>&nbsp;</div>').load(url);
	};


	jQuery(document).ready(function($)
	{
		/*jQuery('.item-block-load-more').trigger('click');*/
		jQuery(".gallery-icon > a").attr("rel", "lightbox");
		jQuery(".size-thumbnail").parent().attr("rel", "lightbox");
		jQuery(".size-medium").parent().attr("rel", "lightbox");
		
		jQuery("a[rel*=lightbox]").colorbox({opacity:0.8,maxWidth:"80%",maxHeight:"98%",slideshow:true,slideshowAuto:false,slideshowSpeed:2500,slideshowStart:"start",slideshowStop:"stop",current: "{current} / {total}"});
		
		jQuery(".help").colorbox({iframe:true, innerWidth:550, innerHeight:400});

		// prevent page body from scrolling when colorbox open
		jQuery(document).bind('cbox_open', function()
		{
			jQuery('body').css('overflow', 'hidden');
			jQuery('body').css('padding-right', '17px');
		}).bind('cbox_closed', function()
		{
			jQuery('body').css('overflow', 'auto');
			jQuery('body').css('padding-right', '0');
		}); 
		
		/* no autocomplete for input fields */
		jQuery(".autocomplete_off").attr("autocomplete", "off");

	});
});


/* LIVE SEARCH */
var currentSelection = -1;
var currentUrl = '';

function performLiveSearch() 
{
	currentSelection = -1;
	currentUrl = '';

	jQuery("#live-search-results").html('<div class="live-search-result-loading">Searching...</div>').slideDown();
	$.ajax(
	{
		url: 'http://www.planet3ds.net/page/' + jQuery('#page').attr('value') + '/',
		data:'live=1&s=' + jQuery('#s').val(),
		type:'GET',
		success: function(data) 
		{
			/*jQuery("#live-search-results").css("display", "none").html(data).slideDown();*/
			jQuery("#live-search-results").html(data).show(); /* .show(): Dirty hack to reopen search results when mouse clicked on next/prev. Fix: need to get not() selector working (see further down). */
		}
	});
}


jQuery(function() 
{
	var timeout = null;
	
	jQuery('#s').keypress(function(e) 
	{
		switch (e.keyCode) 
		{
			case 38: //up
				navigate('up');
				break;

			case 40: //down
				navigate('down');
				break;
				
			case 13: //enter
				if(currentUrl == '#next') 
				{
					jQuery('#page').attr('value', parseInt(jQuery('#page').attr('value')) + 1);
					performLiveSearch();
					return false;
				}
				else if(currentUrl == '#prev') 
				{
					jQuery('#page').attr('value', parseInt(jQuery('#page').attr('value')) - 1);
					performLiveSearch();
					return false;
				}								
				else if(currentUrl != '') 
				{
					window.location = currentUrl;
				}
				break;

			default: //else
				if(timeout) clearTimeout(timeout);
				jQuery("#live-search-results").html('<div class="live-search-result-loading">Readying Search...</div>').slideDown();
				timeout = setTimeout(function()
				{
					if( jQuery("#s").val().length >= 3 )
					{
						jQuery('#page').attr('value', 1);
						performLiveSearch();
					}
					else if( jQuery("#s").val().length > 0 )
					{
						jQuery("#live-search-results").html('<div class="live-search-result-notice">Your search term has to be at least 3 characters long</div>');
					}
					else
					{
						jQuery("#live-search-results").slideUp();
					}
				}, 300);
				break;
		}
	});
	
	jQuery("#searchform").submit(function()
	{
		if(currentUrl != '') return false;
	});
	
	/* not() selector not working apparently. currently solved by a workaround in performLiveSearch() function */
	jQuery("div").not("#searchform").click(function()
	{
		jQuery("#live-search-results").hide();
	});

	// Make the search results (re)appear when clicking on the search box
	jQuery("#s").click(function()
	{
		if(jQuery("#live-search-results").html() != '') jQuery("#live-search-results").show();
		return false;
	});
	
});

function navigate(direction) 
{
	// Check if any of the menu items is selected
	if(direction == 'up') 
	{
		if(currentSelection <= 0)
		{
			currentSelection = (jQuery("#live-search-results a").size() - 1);
		}
		else
		{
			currentSelection--;
		}
	} 
	else if (direction == 'down')
	{
		if(currentSelection == jQuery("#live-search-results a").size() - 1)
		{
			currentSelection = 0;
		}
		else
		{
			currentSelection++;
		}
	}
	setSelected(currentSelection);
}

function setSelected(menuitem)
{
	jQuery("#live-search-results a").removeClass("itemhover");
	if(menuitem >= 0) jQuery("#live-search-results a").eq(menuitem).addClass("itemhover");
	currentUrl = jQuery("#live-search-results a").eq(menuitem).attr("href");
}
