$('document').ready(
function()
{
	loadSideBarArticles("most_popular");

	updateSearchLink();
	$('#searchBox').change(updateSearchLink);

	// Have the enter key when pressed in the search box follow the link
	$('#searchBox').keypress(function(e)
	{
		if(e.which == 13)
		{
			updateSearchLink();
			var searchLink=$('#searchLink').attr('href');
			javascript:window.location = searchLink;
		}
	});

});

function loadLoginForm()
{
	$.getJSON("/shared_ajax/loadLoginForm",
	function(result)
	{
		$("#loginBar").html(result.loginForm);	

		var options={
			beforeSubmit: loginFormSetup,
			success: loginFormResult,
			dataType: "json"};

		$("#topLogin").ajaxForm(options);
	});
}

function loginFormSetup()
{


}

function loginFormResult(result)
{
	$.getJSON("/shared_ajax/cookieCheckerSet",
	function()
	{
		$.getJSON("/shared_ajax/cookieCheckerGet",
		function(result)
		{
			if(!result.success)
			{
				loadAlert("Your cookies are disabled, this may create a problem with your login");
			}
		});
	});


	if(result.success == true)
	{
		$("#loginBar").html(result.loginBar);
	}
	else
	{
		loadAlert(result.error);
	}

}

function updateSearchLink()
{
	var searchText=$('#searchBox').val();

	searchText=jQuery.trim(searchText);	

	var searchString="/search/"+encodeURIComponent(searchText).replace(/%20/g, '+');

	$('#searchLink').attr('href',searchString);
}

function loadSideBarArticles(type)
{
	$.getJSON("/shared_ajax/sideBarArticles/"+type,
	function(result)
	{
		$("#relatedArticles").html(result.sideBarArticles);
	});
}

function loadAlert(alertContent)
{
	var alertText='<div class="decoratedBox ac_box">';
	alertText+='<h3><img src="/assets/img/error.png" />Attention!</h3>';
	alertText+='<p>'+alertContent+'</p>';
	alertText+='<input class="largebutton" id="closeButton" type="button" value="Close">';
	alertText+='</div>';

	$("#popupBodyAlert").html(alertText);

	$('#closeButton').click(function(){disablePopup("Alert");});
	
	centerPopup(null,"Alert");
	loadPopup("Alert");
}
