eventer (window, 'load', init, false);
var user = new Object();
var currentView = 'rfl';

function init(e) {
    e = new Evt(e);
    if (nodeOf('menu-data')) {
	build(nodeOf('menu-data'));
    }
    _call_UserLogin(0);
}

function _call_UserLogin(mode) {
    var the_call = '';

    switch (mode) {
    case 0: // just check if logged in
	break;
    case 1: // login
	var uname = nodeOf('user-login').value;
	var passw = nodeOf('user-password').value;
	the_call = 'user_login=' + uname + '&user_password=' + passw;
	break;	
    case 2: // logout
	the_call = 'out=1';
	clearPrivateViews();
	break;
    case 3: // login with id
	the_call = 'uid=' + user.id;
	break;
    }

    var client = createClient();
    client.onreadystatechange = function() {
	if (client.readyState == 4 && client.status == 200) {
	    user = JSON.parse(client.responseText);
	    //alert(describe(user));
	    if (!user.id) {
		if (mode != 1) reloadMenu();
		else alert('Wrong credentials!');
	    } else if (mode == 3) {
		_call_UserCheckReferred();
	    }
	    reloadMenu();
	}
    };
    client.open('POST', baseURL + 'user-login.php', true);
    client.setRequestHeader("Content-type",
			    "application/x-www-form-urlencoded");
    client.setRequestHeader("Content-length", the_call.length);
    client.setRequestHeader("Connection", "close");
    client.send(the_call);
}

function _call_UserCheckReferred() {
    var client = createClient();
    client.onreadystatechange = function() {
	if (client.readyState == 4 && client.status == 200) {
	    user = new Object();
	}
    };
    var the_call = 'uid=' + user.id;
    client.open('POST', baseURL + 'user-check-referred.php', true);
    client.setRequestHeader("Content-type",
			    "application/x-www-form-urlencoded");
    client.setRequestHeader("Content-length", the_call.length);
    client.setRequestHeader("Connection", "close");
    client.send(the_call);
}

function login(e) {
    _call_UserLogin(1);
}

function logout(e) {
    _call_UserLogin(2);
}

function register(e) {
    view('registration');
}

function reloadMenu() {
    var menu = nodeOf('login');
    while (menu.hasChildNodes()) {
	menu.removeChild(menu.childNodes[0]);
    }
    if (user.id) {
	var out = elementize('input', 
			     'type=button',
			     'className=button', 
			     'value=Logout'); 
	eventer(out, 'click', logout, false);
	foster(menu, out);
	//nodeOf('challenges-menu').style.display = 'inline';
	//nodeOf('results-menu').style.display = 'inline';
	view('rfl');
    } else {
	var uname = elementize('input', 'type=text', 
			       'id=user-login',
			       'name=user_login',
			       'className=field',
			       'value=Username');
	var passw = elementize('input', 'type=password', 
			       'id=user-password',
			       'name=user_password',
			       'className=field',
			       'value=         ');
	var submit = elementize('input', 
				'type=button', 
				'className=button',
				'value=Login');
	eventer(submit, 'click', login, false);
	var reg = elementize('input', 
			     'type=button', 
			     'className=button',
			     'value=Register');
	eventer(reg, 'click', register, false);
	foster(menu, uname, passw, submit, reg);
	view('rfl');
	//nodeOf('challenges-menu').style.display = 'none';
	//nodeOf('results-menu').style.display = 'none';
    }
}

function build(node) {
    //alert(node.id);
    for (var i=0; i<node.childNodes.length; i++) {
	var child = node.childNodes[i];
	if (child.nodeType == 3) continue;
	if (!child.id) continue;
	if (child.getAttribute('nobuild') == 1) continue;
	if (this['build_' + child.id]) {
	    this['build_' + child.id]();
	}
	build(child);
    }
}

function build_table(node) {
    // Header
    var titles = eval (node.id + '_headers');
    if (titles.length) {
	var header = elementize('tr');
	for (var i=0; i<titles.length; i++) {
	    foster(header, elementize('th', 'innerHTML=' + titles[i]));
	}
	foster(node, foster(elementize('thead'), header));
    }

    // Body
    foster(node, elementize('tbody', 'id=' + node.id + '_contents'));
}

function build_rfl() {
    var node = nodeOf('rfl');
    ajax('Display', 'races-from-location', node);
}

function build_results() {
    var node = nodeOf('results');
    ajax('Display', 'user-results', node);
}

function build_challenges() {
    var node = nodeOf('challenges');
    ajax('Display', 'user-challenges', node);
}

function build_registration() {
    var node = nodeOf('registration');
    ajax('Display', 'user-registration', node);
}

function view(id) {
    if (id == currentView) return;
    if (!user.id && (id == 'challenges' || id == 'results')) {
	alert('You must be logged in to view this page.');
	return;
    }
    nodeOf(currentView).style.display = 'none';
    currentView = id;
    var node = nodeOf(id);
    node.style.display = 'block';
    if (!node.hasChildNodes()) {
	this['build_' + id]();
    }
}

function clearPrivateViews() {
    var nodes = new Array(nodeOf('challenges'), nodeOf('results'));
    for (var i=0; i<nodes.length; i++) {
	var node = nodes[i];
	while (node.hasChildNodes()) {
	    node.removeChild(node.childNodes[0]);
	}
    }
}

function info(msg) {
    nodeOf('info').innerHTML += msg + '<br>';
}

function pleaseWait(state) {
    var body = tags(document, 'body')[0];
    //clearTimeout(pleaseWait.timer);
    if (!pleaseWait.node) {
	pleaseWait.node = elementize('div', 'id=please-wait-fs');
	var overlay = elementize('div', 'className=please-wait-overlay');
	var loading = elementize('div', 'className=please-wait-loading');
	foster(body, 
	       foster(pleaseWait.node, overlay, loading));
	setPos(pleaseWait.node, 0, 0);
	//pleaseWait.timer = null;
    }
    var node = pleaseWait.node;
    if (state) {
	//setOpacity(node, 0);
	var overlay = tags(node, 'div')[0];
	var loading = tags(node, 'div')[1];
	setPos(pleaseWait.node, scrollPos()[0], scrollPos()[1]);
	node.style.display = 'block';
	setY(loading,
	     (getOH(node)-getOH(loading))/2);
	/*
	pleaseWait.timer = 
	    setInterval('fadeIn("' + node.id + 
			'", "pleaseWait.timer", .1)', 50);
	*/
    } else {
	/*
	pleaseWait.timer = 
	    setInterval('fadeOut("' + node.id + 
			'", "pleaseWait.timer", .1)', 50);
	*/
	node.style.display = 'none';
    }
}

var fadeTimer;
var currentDetailView;
function detailView(node) {
    currentDetailView = node;
    node.style.display = 'block';
    setPos(node, 0, 0);
    var overlay = nodeOf(node.id + '_overlay');
    setOpacity(overlay, .9);
    var content = nodeOf(node.id + '_content');
    setOpacity(content, 0);
    fadeTimer = setInterval('fadeIn("' + content.id + 
			    '", "fadeTimer", .1)', 50);
}

function closeDetailView() {
    var node = currentDetailView;
    node.style.display = 'none';
    var overlay = nodeOf(node.id + '_overlay');
    setOpacity(overlay, 0);
    var content = nodeOf(node.id + '_content');
    setOpacity(content, 0);
}