// function to let user login
$(document).on('submit','#login-form',function(e)
{
	e.preventDefault();
	if($('body').hasClass('in_process')){ return false; }

	username = $('#username').val();
	password = $('#password').val();
	form_error = false;

	if($.trim(username).length == 0)
	{
		if($('#username').siblings('p.text-danger').length == 0)
		{
			$('<p class="text-danger">Username is mandatory</p>').insertAfter($('#username'));
		}
		$('#username').addClass('red-border');
		form_error = true;
	}
	else
	{
		$('#username').removeClass('red-border');
		$('#username').siblings('p.text-danger').remove();
	}

	if($.trim(password).length == 0)
	{
		if($('#password').siblings('p.text-danger').length == 0)
		{
			$('<p class="text-danger">Password is mandatory</p>').insertAfter($('#password'));
		}
		$('#password').addClass('red-border');
		form_error = true;
	}
	else
	{
		$('#password').removeClass('red-border');
		$('#password').siblings('p.text-danger').remove();
	}

	if(form_error == true)
	{
		return false;
	}

	url = $(this).attr('action');
	$('#login-submit').siblings('p.text-danger').remove();
	$('body').addClass('in_process');
	$('.ibox-content').addClass('sk-loading');

	$.ajax(
	{
		url: url,
		type: 'POST',
		data: new FormData(this),
		processData: false,
		contentType: false,
		cache: false,
		success: function(data)
		{
			response = JSON.parse(data);
			$('.ibox-content').removeClass('sk-loading');
			if(response.status == 'error')
			{
				$('body').removeClass('in_process');
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 5000 };
				toastr.error(response.message, 'Error');
			}

			if(response.status == 'success')
			{
				toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 2000 };
				toastr.success(response.message, 'Success');
				setTimeout(function()
				{
					window.location.href = response.redirect_url;
				}, 1000);
			}
		},
		error: function(data)
		{
			$('.ibox-content').removeClass('sk-loading');
			$('body').removeClass('inprocess');
			toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 };
			toastr.error('Please try after some time.', 'Unknown Error');
		}
	});
});