login_popup = (function () {
	
	var 
		$ = jQuery,
		colors = {           // text colors for input fields 
			placeholder: '#888',
			placeholder_faded: '#ccc',
			normal: '#000'
		},
		displayed = false,   // whether the form is displayed 
		error_field,         // div for error messages 
		error_timer,         // interval for values change check 
		form,                // the login form, also being the popup  
		initialized = false, // whether initialization was done (on first form displaying) 
		loading,             // loading gif 
		password,            // password field 
		submitting = false,  // whether the form is in the proccess of submission 
		username            // username field 
	;
	function error(msg) { // shows or removes an error message 
		if (!msg) { // replace error message with a button 
			
			// cover cases when value is changed using contextual menu 
			if (error_timer) clearInterval(error_timer);
			error_field.animate({ opacity: 0 }, 'fast', function () {
				error_field.hide().html('');
				form.find('button').show().animate({ opacity: 1 }, 'fast');
			});
			
		}
		else { // replace button with an error message 
			
			var 
				bad_username = username.val(),
				bad_password = password.val()
			;
			
			// cover cases when value is changed using contextual menu 
			if (error_timer) clearInterval(error_timer);
			error_timer = setInterval(function () {
				if (username.val() !== bad_username || password.val() !== bad_password) {
					error();
				}
			}, 100);
			
			form.find('button').animate({ opacity: 0 }, 'fast', function () {
				form.find('button').hide();
				error_field.html('<i>!</i>' + msg).show().animate({ opacity: 1 }, 'fast');
			});
			
		}
	}
	function hide(e) {
		if (e.which && e.which == 3 || e.button && e.button == 2) { // don't close on right click 
			return false;
		}
		form.fadeTo('fast', 0, function () {
			this.style.display = 'none';
		});
		displayed = false;
		$(document).unbind('click', hide);
		if (e.preventDefault) e.preventDefault();
		return false;
	}
	function init() { // sets up DOM references and event handlers 
		form = $('#login_popup');
		error_field = form.find('div.error');
		username = form.find('input[name=username]');
		password = form.find('input[name=password]');
		error_field = form.find('div.error');
		loading = form.find('img');
		form.click(stopPropagation).submit(submit);
		username.bind('focus blur keydown', function (e) {
			return placeholder_handler(e, 'Username', 'text');
		}).trigger('blur');
		password.bind('focus blur keydown', function (e) {
			return placeholder_handler(e, 'Password', 'password');
		}).trigger('blur');
		initialized = true;
	}
	function moveCaret(field, pos) { // moves input's caret to specified position 
		if (field.setSelectionRange) {
			field.focus();
			field.setSelectionRange(pos, pos);
		}
		else if (field.createTextRange) {
			var range = field.createTextRange();
			range.collapse(true);
			range.moveEnd('character', pos);
			range.moveStart('character', pos);
			range.select();
		}
	}
	function placeholder_handler(e, placeholder, inp_type) { // handles placeholder values 
		
		var 
			color, // color to be set 
			el = e.target,
			inp_type = inp_type || el.type
		;
		if (e.type === 'focus' && el.value === placeholder) {
			// Clear the selection. Put the carriage to the beginning of the field.
			setTimeout(function () {
				moveCaret(el, 0);
			}, 1);
			$(el).stop().animate({ color: colors.placeholder_faded });
		}
		else if (e.type === 'keydown') { // hide the placeholder, convert password field 
			var character = String.fromCharCode(e.keyCode);
			
			if ( // if a key pressed is not a controll one, hide placeholder and change color 
			e.keyCode !== 9 && e.keyCode !== 16 && e.keyCode !== 17 && 
			e.keyCode !== 18 && e.keyCode !== 91 &&
			(e.keyCode !== 10 && e.keyCode !== 13 || e.nodeName === 'TEXTAREA')
			) {
				
				if (el.value === placeholder) { // hide placeholder 
					el.value = '';
					if (inp_type === 'password') {
						try {
							el.type = 'password';
						} catch (e) { // the stupid browser, have to replace the field 
							
							$(el).after('<input type="password" name="password" value="" />').detach();
							password = form.find('input[name=password]');
							el = password.get(0);
							password.bind('focus blur keydown', function (e) {
								return placeholder_handler(e, 'Password', 'password');
							});
							if (character) {
								el.value = character;
								moveCaret(el, 1);
							}
							setTimeout(function() { el.focus(); }, 10);
						}
					}
				}
				$(el).stop().css('color', colors.normal);
				
			}
			
		}
		else if (e.type === 'blur') {
			if (el.value === '') { // show the placeholder 
				el.value = placeholder;
				if (inp_type === 'password') {
					try {
						el.type = 'text';
					} catch (e) { // the stupid browser 
						$(el).after('<input type="text" name="password" value="Password" />').detach();
						password = form.find('input[name=password]');
						el = password.get(0);
						password.bind('focus blur keydown', function (e) {
							return placeholder_handler(e, 'Password', 'password');
						});
					}
				}
			}
			
			if (el.value === placeholder) {
				$(el).stop().animate({ color: colors.placeholder });
			}
			else {
				$(el).stop().css('color', colors.normal);
			}
		}
	}
	function show(e) { // shows the form 
		if (!initialized) init();
		if (displayed) return hide(e);
		
		form.css('display', 'block').fadeTo('fast', 0.95);
		username.focus().select();
		displayed = true;
		$(document).click(hide);
		e.cancelBubble = true; // IE event object 
		if (e.stopPropagation) e.stopPropagation();
		if (e.preventDefault) e.preventDefault();
		return false;
	}
	function stopPropagation(e) { // used to avoid hiding on clicking the popup 
		e.stopPropagation();
	}
	function submit(e) {
		if (submitting) { // only one submission at a time 
			e.preventDefault();
			return false;
		}
		error(); // remove error message if any 
		var form_node = form.get(0);
		if (!username.val() || username.val() === 'Username') { // focus empty field 
			username.focus();
			e.preventDefault();
			return false;
		}
		if (!password.val() || password.val() === 'Password') { // focus empty field 
			password.focus();
			e.preventDefault();
			return false;
		}
		submitting = true;
		loading.show();
		$.ajax({
			type: 'POST',
			url: '/login.php',
			data: form.serialize(),
			dataType: 'text',
			success: function (resp) {
				switch (resp) {
					case 'ok'      : location.href = '/club_t4t.php'; break;
					case 'wrong'   : error('Wrong Username or Password'); break;
					case 'expired' : error('Your account has expired'); break;
					default        : error('Unexpected error');
				}
				loading.hide();
				submitting = false;
			},
			error: function () {
				error('Connection failure');
				loading.hide();
				submitting = false;
			}
		});
	}
	
	return {
		show: show
	};
	
}());
