var timer;

// define main observer
Event.observe(window, 'load', init, false);

function init() {
	disableOkButton();
	
	//observe username field
	if ($('userName') != null) {
		$('userName').observe('keyup', testLength);
		$('userName').observe('focus', noErrorMsg);	
		
	}
	if ($('loginPwd') != null) {
		$('loginPwd').observe('keydown', testUsername);	
		$('loginPwd').observe('keyup', toggleOkButton);
	}
	
	// test username
	testLength();
	
}

function setLink(link) {
	ajaxLink = link;
}

function testLength() {
	if ($('userName') != null) {
		var username;
		username = $('userName').getValue();
		if (username.length > 3) {
			setUpdateFormTimer(username);
		} else {
			$('loginForm').action = "";
			disableOkButton();
		}
	}
}

function testUsername() {
	setTimeout("errorMsg()", 900);
}

function setUpdateFormTimer(username) {
	// if there is already a timer, clear it first
	if (timer != null) {
		clearTimeout(timer);
	} 
	timer = setTimeout("updateFormAction()", 300);
}

function updateFormAction() {
	// check input of user
	username = $('userName').getValue();
	var reg = new RegExp("^[a-zA-Z0-9_@-]+$");
    if (reg.test(username)) {
		// send axjax request to server to check username
		new Ajax.Request( ajaxLink, {
        parameters: {
            'username': username,
        },
        method: 'get',
        onSuccess: function(transport) {
            var url = transport.responseText;
			// update action if url defined
			if (typeof(url) !== 'undefined' && url != null && url != "") {
				$('loginForm').action = url;
			} else {
				// set to empty string again, disable ok button
				$('loginForm').action = "";
				disableOkButton();
			}
        },
		
		onFailure: function(transport) {
			$('loginForm').action = "";
			disableOkButton();
        }
		});	
	}
}

function errorMsg() {
	if ($('loginForm').action == "") {
		$('loginError').setStyle({'display': 'block', 'color': '#0072BA'});
	}
}

function noErrorMsg() {
	$('loginError').setStyle({'display': 'none'});
}

function toggleOkButton() {
	if ($('loginPwd').getValue() != "" && $('loginPwd') != null && $('loginForm').action != "") {
		enableOkButton();
	} else {
		disableOkButton();
	}
}


function disableOkButton() {
	if ($('okButton') != null) {
		$('okButton').disabled = 1;
		$('okButton').setStyle({'cursor': 'default'});
	}
}

function enableOkButton() {
	$('okButton').disabled = 0;
	$('okButton').setStyle({'cursor': 'pointer'});
}