var ajax_auth_page_needs_to_be_refreshed = false;

function ajax_auth_login()
{
	var user_id = $('#username').val();
	//var password = $('#pw').val();
	var password = $('#password').val();
	var remember_me = $('#remember_me').is(':checked') ? 1 : 0;
	
	var postvars = {"user_id" : user_id, "password" : password, "remember_me" : remember_me};
	
	if ($('div.notify').text() != '')
	{
		$('div.notify').text('Authenticating...');
	}

	$.post('/mobile/auth/ajax_auth_login', postvars, function(data)
	{
		if ($('div.notify').text() != '')
		{
			$('div.notify').text('Success! Loading...');
		}
		
		$('div#button_login_spinner').hide();
		$('#button_login').show();
		
		if (data.status == 'success')
		{
			if (data.location == undefined)
			{
				window.location = "/mobile/maintenance" + '?nocache=' + String(new Date().getTime()) + String(Math.random());
			}
			else
			{
				window.location = data.location + cache_buster();
				ajax_auth_page_needs_to_be_refreshed = true;
			}
		}
		else
		{
			$('div.notify').text(data.message);
			$('div.notify').fadeIn(400);
			//$('div.notify').show(500);
		}
	}, 'json');
}

function cache_buster()
{
	return '?nocahe=' + String(new Date().getTime()) + String(Math.random());
}

function ajax_auth_logout()
{
	$.post('/mobile/auth/ajax_auth_logout' + '?nocache=' + String(new Date().getTime()) + String(Math.random()), function(data)
	{
		//alert(data.location);
		
		if(typeof(data.location) == 'undefined')
		{
			window.location = "/mobile" + cache_buster();
		}
		
		else if(data.location == null)
		{
			window.location = "/mobile";
		}
		
		else
		{
			window.location = data.location + cache_buster();
		}
	}, 'json');
}

$(function ()
{
	if (ajax_auth_page_needs_to_be_refreshed)
	{
		ajax_auth_page_needs_to_be_refreshed = false;
		window.reload();
	}
});