if ( typeof Plastic === "undefined" ) {
	var Plastic = {};
}

$( function() {
	
	$.ajaxSetup( {
		dataType: "json"
	} );
	
	$("#session-login").submit( function( e ) {
		
		e.preventDefault();
		// TODO: should error handling be moved into the view? probably
		$("#session-login-error").html("&#160;");
		$(document).trigger("userBusy");
		
		$.ajax( {
			type: "POST",
			url: "/api/",
			dataType: "json",
			data: {
				method: "logIn",
				identifier: $("#session-login-identifier").val(),
				password: $("#session-login-password").val(),
				remember: $("#session-login-remember").is(":checked")
			},
			success: function( response ) {
				if ( response.successful ) {
					Plastic.User = response.data;
					$(document).trigger("userLoggedIn");
				} else {
					$.each( response.errors, function( field, msg ) {
						$("#session-login-error").html( msg );
						return false;
					} );
				}
			},
			error: function( xhr, textStatus, errorThrown ) {
				$("#session-login-error").html( "Unknown error\u2014please try again" );
			},
			complete: function() {
				$(document).trigger("userUnbusy");
			}			
		} );
	} );
	
	$("#session-welcome-logout").submit( function( e ) {
		e.preventDefault();
		$(document).trigger("userBusy");
		$.ajax( {
			type: "POST",
			url: "/api/",
			dataType: "json",
			data: {
				method: "logOut"
			},
			success: function( response ) {
				if ( response.successful ) {
					Plastic.User = null;
					$(document).trigger("userLoggedOut");
				} else {
					// No error conditions have been defined
				}
			},
			error: function() {
				// TODO: should probably notify the user that they weren't logged out
			},
			complete: function() {
				$(document).trigger("userUnbusy");
			}			
		} );
	} );
	
} );
