// Functionality local to the boards
var boards = {
	// A valid UID is one which is not currently in use AND well-formed
	isValidUID : function (uid, callback) {
		if (!uid) {
			return false;
		}

		var uid = uid.trim();

		if (uid !== "") {
			var options = {
				parameters : "username=" + uid,
				onComplete : function (transport) {
					var isValid = -1;

					try {
						// NOTE: transports with a status other than 200 are assumed to be errors
						// e.g. 500 is system error, 0 is an aborted transport
						if (transport.status == 200) {
							isValid = (transport.responseText > 0) ? 0 : 1;
						}
					} catch (err) {
						// NOTE: Firefox silently throws an error when accessing the status member
						//			 of aborted transports. This error will not appear in the Error Console or
						//			 Firebug BUT we can catch it... go figure.  For this implementation we don't
						//			 need to do anything here beside suppress the error.
					}

					if (callback) {
						callback(isValid);
					}
				}
			};

			var ajax = new Ajax.Request("/Ajax/IsValidUID.ashx", options);
			// NOTE: we do this monkey dance b/c Prototype does not support aborting a request after a timeout period
			var timeoutId = window.setTimeout(function () {
				window.clearTimeout(timeoutId);
				if (ajax.transport.readyState == 4) {
					return;
				}
				ajax.transport.abort();

				if (window.opera || ajax.transport.readyState == 1) {
					// NOTE: After a transport is aborted Opera (8/9) will not execute the onComplete callback. Do it manually.
					// NOTE: Safari 2 sets readyState to 1 for aborted transports. FFX, IE, Opera set it to zero
					options.onComplete({status:0});
				}
			}, 5000); // 5 seconds
		}
	},
	// Register.ascx
	register : {
		uid : {
			input : null,
			output : null,
			link : null,
			isProcessing : false,
			throttle : {
				delay : 500, // ms
				last : null
			},
			// handle isValidUID callback
			callback : function (status, uid) {
				this.isProcessing = false;
				var message, className = "fieldHelp ";
				switch (status) {
					case 0 :
						message = uid + " is available";
						className += "uidValid";
						break;
					case 1 :
						message = uid + " is unavailable";
						className += "uidInvalid";
						break;
					default :
						message = "Sorry we're having some technical difficulties, please try again.";
						className += "uidError";
						break;
				}
				this.output.innerHTML = message;
				this.output.className = className;
			},
			// handle UI events
			controller : function (event) {
				this.link.blur();
				var uid = this.input.value || "";
				uid = uid.trim();

				// only one connection at a time
				if (this.isProcessing || uid == "") { return; }
				// throttle http requests
				var current = new Date().getTime();
				if (this.throttle.last != null && ((current - this.throttle.last) < this.throttle.delay)) { return; }

				this.throttle.last = current;
				this.isProcessing = true;
				this.output.innerHTML = "Checking availability ...";
				this.output.className = "fieldHelp uidLoading";
				boards.isValidUID(uid, function (status) {
					boards.register.uid.callback(status, uid);
				});
			},
			// prepare the UID check
			prepare : function () {
				this.output = $("checkUsername");
				this.input = this.output.previousSibling;
				if (this.input.nodeType != 1) { this.input = this.input.previousSibling;}

				// inject into UI w/ old skool write
				var id = "__" + new Date().getTime() + "__";
				document.write("<a href='javascript:void(0);' class='chkAvailable' id='" + id + "'>Username available?</a>");

				this.link = $(id);
				this.input.onblur = this.controller.bindAsEventListener(this);
				this.link.onclick = this.controller.bindAsEventListener(this);
			}
		}
	}
};


// find a better place to put this call

// fix this so it doesn't error on ukmf boards
if(typeof Fool == 'object') { 
	// Adjust for small monitors
	Fool.onLoad(Fool.Util.setLayout);
	Fool.onResize(Fool.Util.setLayout);
}

// TODO: Fix this nonsense - ksmith
var inhibit = false;
var keyboardNav = function(evt) {
    var key = evt.keyCode;
    if (!inhibit) {
        var nextLink = $$('.nextLink')[0];
        var previousLink = $$('.previousLink')[0];
        // Previous link keyboard navigation , or \ browses previous.
        if (key == 220 || key == 188) {
            if (previousLink) {
                location.href = previousLink.href;
            }
        }
        // Next link keyboard navigation . or enter browses next.
        if (key == 13 || key == 190) {
            if (nextLink) {
                location.href = nextLink.href;
            }
        }
    }
}
$(document).observe('keydown', keyboardNav);
