
var PAGE = new function() {
	this.init = function() {
		if (typeof(username)=="string" && username.length > 0){
			this.ShowUsername(username);
		}else{
			$n = jQuery(".deallogin");
			$n.find("input[name='user']").keydown(login_entry);
			$n.find("input[name='password']").keydown(login_entry);
		}
	};
	
	var login_entry = function(e) {
		//console.dir(e);
		var charCode = e.charCode ? e.charCode : e.keyCode;
		if (charCode == 13) {
			e.preventDefault();
			return false;
		}
	};

	this.SignIn = function() {
		var fn_on_ajax_success = function(obj) {
			//console.dir(obj);
			if (obj.result == "OK" && ("customer" in obj)) {
				PAGE.ShowUsername(obj.customer.username);
			} else {
				alert("Sorry! Sign in failed. Please verify your credentials and try again.");
			}
		};

		var un, pw;
		un = _form.elements["user"].value.trim();
		pw = _form.elements["password"].value.trim();
		var re = /"/g;

		$.ajax({
			url: BASE_URL +"ajax.aspx?id=sign-in", type: "POST", //contentType: "application/json",
			dataType: "json",
			data: "JSON=" + escape("{\"username\":\"" + un.replace(re, "\\\"") + "\",\"password\":\"" + pw.replace(re, "\\\"") + "\",\"echo\":\"\"}"),
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("Error!\n" + textStatus + "\n" + errorThrown);
				//console.dir(XMLHttpRequest);
			},
			success: function(data, textStatus) {
				//alert("HTTP "+ this.type +"\n"+ textStatus +"\n"+ typeof(data));
				//console.dir(data);
				if (!("error" in data)) fn_on_ajax_success(data);
				else alert("Error!\n" + data.error);
			},
			complete: function(XMLHttpRequest, textStatus) {
				//alert("Complete.\n"+ textStatus);
			}
		});
		
		return false;
	};
	
	this.ShowUsername = function(username){
		jQuery(".deallogin").html("<h3>Welcome!</h3>You are signed in as <a href=\""+ BASE_URL +"pages/customer.aspx\">"+ username +"</a>");
	};

};

