jQuery(document).ready( function($) {
 	//Oh well... I guess we have to use jQuery ... if you are a javascript developer, consider MooTools if you have a choice, it's great!
	//I'm biased, but form functionality already comes prepacked with MooTools :) 	
 	$('#LoginWithAjax_Form').submit(function(event){
		//Stop event, add loading pic...
		event.preventDefault();
		$('<div id="LoginWithAjax_Loading"></div>').prependTo('#login-with-ajax');
		//Sort out url
		url = $('#LoginWithAjax_Form').attr('action');
		url += (url.match(/\?/) != null) ? '&callback=?' : '?callback=?' ;
		url += "&log="+$("#lwa_user_login").attr('value');
		url += "&pwd="+$("#lwa_user_pass").attr('value');
		url += "&login-with-ajax=login";
		$.getJSON( url , function(data, status){
			$('#LoginWithAjax_Loading').remove();
			if( data.result === true || data.result === false ){
				if(data.result == '1'){
					//Login Successful
					if( $('#LoginWithAjax_Status').length > 0 ){
						$('#LoginWithAjax_Status').attr('class','confirm').html("Login Successful, redirecting...");
					}else{
						$('<span id="LoginWithAjax_Status" class="confirm">Login Successful, redirecting...</span>').prependTo('#login-with-ajax');
					}
					if(data.redirect == null){
						window.location.reload();
					}else{
						window.location = data.redirect;
					}
				}else{
					//Login Failed
					//If there already is an error element, replace text contents, otherwise create a new one and insert it
					if( $('#LoginWithAjax_Status').length > 0 ){
						$('#LoginWithAjax_Status').attr('class','invalid').html(data.error);
					}else{
						$('<span id="LoginWithAjax_Status" class="invalid">'+data.error+'</span>').prependTo('#login-with-ajax');
					}
				}
			}else{	
				//If there already is an error element, replace text contents, otherwise create a new one and insert it
				if( $('#LoginWithAjax_Status').length > 0 ){
					$('#LoginWithAjax_Status').attr('class','invalid').html('An error has occured. Please try again.'+status);
				}else{
					$('<span id="LoginWithAjax_Status" class="invalid">An error has occured. Please try again.</span>').prependTo('#login-with-ajax');
				}
			}
		});
	});	
});