/* http://developer.mozilla.org/en/docs/AJAX */
var http_request = null;
var container = null;
var users = null;
var ids = null;
var userDOM = null;
var uId = 0;

var AVATAR_DIR = "http://forums.vc-lan.org/images/avatars/";

var date = new Date();

function user() {
	var name = "";
	var uid = 0;
	var iid = 0;
	var xfire = "";
	var age = 0;
	var username = "";
	var bio = "";
	var info = "";
	var fullyLoaded = false; /* This tells us if we need to grab more data */
	var loadTime = 0;
}

function start() {
	try {
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } catch(e) { failed(); }
    
    try {
    	http_request.overrideMimeType('text/xml');
    } catch(e) {}
	
	if (!getDom()) return;
	
	try {
    	/* Load the list of users first */
    	http_request.open('GET', 'profile_ajax.php?get=list', true);
    	http_request.onreadystatechange = function(){
    		loadUsers();
    	};
    	http_request.send(null);
	} catch (e) { failed(); }
}

function getDom() {
	try {
		container = document.getElementById('aboutus');
		return true;
	} catch (e) {
		failed();
		return false;
	}
}

function loadUsers() {
	try {
    	/* If it isn't 4, then there is no point yet... */
        if (http_request.readyState != 4) return;
    	
    	if (http_request.status != 200) {
    		failedErr("There was a problem with loading this list. Please try again later.");
    		return;
    	}
	} catch(e) {
		failedErr("Unknown error.");
		return;
	}
	
	http_request.onreadystatechange = function() {};
	
	try {
    	var xmldoc = http_request.responseXML;
    	var root = xmldoc.getElementsByTagName('list').item(0);
	} catch(e) {
		failedErr("There was a problem with loading the list. Try refreshing the page.");
	}
	
	/* Reset the users and ids array */
	users = new Array();
	ids = new Array();
	
	/* Loop through XML and load the basic user data, names and such */
	for(var i=0; i<root.childNodes.length; i++)
		if (root.childNodes[i].nodeName == "item")
			loadUser(root.childNodes[i], false);
	
	if (users.length > 0)
		displayUsers();
	else
		failedErr("No users were found from the database. That's odd. Try again later when your Magic 8 Ball says so.");
}

function displayUsers() {
	var s = "<table class='users'><tr><td width='100'><div style='width:100%;font-weight:bold;'>Clan Members</div><ul class='userList'>";
	for(var i=0; i<ids.length; i++)
		s += "<li onclick=\"Javascript:showUser(" + ids[i] + ");\"><a href=\"Javascript:void(0);\" onclick=\"Javascript:showUser(" + ids[i] + ");\">" + users[ids[i]].name + "</a></li>";
	s += "</ul></td><td><div id=\"userDOM\">Click on a name on the left to see something that you probably don't want to know.</div></td></tr></table>";
	
	container.innerHTML = s;
	userDOM = null;
	userDOM = document.getElementById('userDOM');
}

function showUser() {
	userDOM.innerHTML = "Loading user information.";
	
	var id = 0;
	if (arguments.length == 0)
		id = uId;
	else
		id = arguments[0];
	
	if (id == 0 || id == null) return;
	
	if (users[id].fullyLoaded == 0 || (users[id].fullyLoaded == 1 && (date.getTime() - users[id].loadTime > 1000*60*60))) { /* Get the user information if it isn't loaded, or if it is older than 1 hour */
		getUserInfo(id);
		return;
	}
	
	uId = 0;
	
	formatUser(id);
}

function formatUser(id) {
	if (typeof(users[id]) != "object") return;
	
	var s = "<table width='100%' class='user'>";
	s += "<tr><td colspan='2' style='text-align:center;font-weight:bold'>" + users[id].name + "</td></tr>";
	
	
	if (users[id].username != "")
		s += "<tr><td colspan='2' style='text-align:center;font-weight:bold'><a href=\"http://forums.vc-lan.org/profile.php?mode=viewprofile&u=" + users[id].uid + "\">" + users[id].username + "</a></td></tr>";
	
	/*if (users[id].original == 1)
		s += "<tr><td colspan='2' style='text-align:center'>An Original Memeber of VCL</td></tr>";*/
	
	if (isAdmin == 1)
		s += "<tr><td colspan='2' style='text-align:center;'><a href=\"profile.php?user_id=" + users[id].uid + "\">Edit Profile</a></td></tr>";
	
	if (users[id].info && users[id].info.user_avatar && (users[id].info.user_allowavatar == "1" || users[id].info.user_allowavatar == 1) && users[id].info.user_avatar != "") {
		s += "<tr><td colspan='2' style='text-align:center;'><img src='";
		if (users[id].info.user_avatar.substr(0, 4).toLowerCase() == "http")
	   		s += users[id].info.user_avatar;
		else
			s += AVATAR_DIR + users[id].info.user_avatar;
		s += "' alt='Avatar' /></td></tr>";
	}
	
	if (users[id].xfire != "")
		s += "<tr><td class='first'><strong>Xfire:</strong></td><td><a href=\"http://www.xfire.com/profile/" + users[id].xfire + "/\">" + users[id].xfire + "</a></td></tr>";
	
	if (users[id].age != "" && users[id].age > 0)
		s += "<tr><td class='first'><strong>Youth:</strong></td><td>" + users[id].age + "</td></tr>";
	
	if (users[id].bio != "")
		s += "<tr><td class='first'><strong>Biography:</strong></td><td>" + users[id].bio + "</td></tr>";
	
	s += "</table>";
	userDOM.innerHTML = s;
}

function getUserInfo(id) {
	try {
		if (http_request.readyState != 4) return; /* In case this gets called more than once while it is loading. Otherwise it will fail with errors */
		
    	/* Load the list of users first */
		uId = id;
    	http_request.open('GET', 'profile_ajax.php?get=user&id=' + id, true);
    	http_request.onreadystatechange = function(){
    		loadUserInfo();
			showUser();
    	};
    	http_request.send(null);
	} catch (e) {
		failedErr("There was a problem loading the user data.");
	}
}

function loadUserInfo() {
	/* If it isn't 4, then there is no point yet... */
	try {
    	if (http_request.readyState != 4) return;
		
		if (http_request.status != 200) {
			failedErr("There was a problem with loading the requested user. Please try again later.");
			return;
		}
	} catch(e) {
		failedErr("Unknown error.");
		return;
	}
	
	http_request.onreadystatechange = function() {};
	
	try {
		var xmldoc = http_request.responseXML;
		var root = xmldoc.getElementsByTagName("user").item(0);
		var u = root.getElementsByTagName("item").item(0);
	} catch(e) {
		failedErr("There was a problem with loading the requested user. Please try again later.");
		return;
	}
	
	loadUser(u);
}

function loadUser(u) {
	var uname = "";
	var name = "";
	var iid = 0;
	var uid = 0;
	var xfire = 0;
	var age = 0;
	var bio = 0;
	var info = "";
	
	var fullyLoaded = (arguments.length > 1 ? arguments[1] : true);
	
	try {
    	var uname = u.getElementsByTagName("username").item(0).childNodes[0].nodeValue;
    	var name = u.getElementsByTagName("name").item(0).childNodes[0].nodeValue;
    	var iid = u.getElementsByTagName("info_id").item(0).childNodes[0].nodeValue;
    	var uid = u.getElementsByTagName("user_id").item(0).childNodes[0].nodeValue;
	} catch(e) { }
	try {
    	var xfire = u.getElementsByTagName("xfire").item(0).childNodes[0].nodeValue;
	} catch(e) { }
	try {
    	var age = u.getElementsByTagName("age").item(0).childNodes[0].nodeValue;
	} catch(e) { }
	try {
    	var bio = u.getElementsByTagName("bio").item(0).childNodes[0].nodeValue;
	} catch(e) { }
	try {
    	var info = parseInfo(u.getElementsByTagName("user_info").item(0));
	} catch(e) { }
	
	if (typeof(users[iid]) == "undefined")
		users[iid] = new user();
	
	users[iid].name = name;
	users[iid].username = uname;
	users[iid].iid = iid;
	users[iid].uid = uid;
	users[iid].xfire = xfire;
	users[iid].age = age;
	users[iid].bio = bio;
	users[iid].info = info;
	users[iid].fullyLoaded = fullyLoaded;
	
	if (fullyLoaded == 1)
		users[iid].loadTime = date.getTime();
	
	ids[ids.length] = iid;
}

function parseInfo(a) {
	var o = {};
	
	for(var i=0; i<a.childNodes.length; i++) {
		if (a.childNodes[i].nodeName != "#text") {
			try {eval("o." + a.childNodes[i].nodeName + " = '" + a.childNodes[i].childNodes[0].nodeValue.replace(/'/,"\'")+ "';"); } catch(e) {}
		}
	}
	
	return o;
}

/*function getTag(db, name) {
	for(var i=0; i<db.childNodes.length; i++) {
		if (db.childNodes[i].nodeName == name)
			if (arguments.length > 2 && arguments[3] == true)
				return db.childNodes[i];
			else
				return (db.childNodes[i].childNodes.length > 0 ? db.childNodes[i].childNodes[0].nodeValue : db.childNodes[i].nodeValue);
	}
	return "";
}*/

function failed() {
	failedErr("Your browser has thrown an error not allowing this page to properly load or function. Please try again in a different browser or wait and reload the page.");
}

function failedErr(msg) {
	if (container == null)
		alert(msg);
	else
		container.innerHTML = msg;
	http_request = null;
	return;
}
