var isMoz = (navigator.appName.indexOf("Netscape") > -1)
var isIE = (navigator.appName.indexOf("Explorer") > -1)
var boxForm, matchID, refID, fieldName, fID;
var context = "";
var nrofminutes = 0;
var name_text = "(nick)name";
var pw_text = "password";
var login_text = "login";
var email_text = "email address";
/*@cc_on
// ie fix [to add exta parameters to setTimeout and setInterval methods] (Andrea Giammarchi)
(function(f){
 window.setTimeout =f(window.setTimeout);
 window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@*/

function getWinDim(){
	var dims = new Object();
	if(isMoz){
		dims.w = window.innerWidth;
		dims.h = window.innerHeight;
	}else if(document.documentElement){
		dims.w = document.documentElement.clientWidth;
		dims.h = document.documentElement.clientHeight;
	}else{
		dims.w = document.body.clientWidth;
		dims.h = document.body.clientHeight;
	}
	return dims;
}

function getElementsByClassName(name, parent){
	var arr = new Array();
	var elmnts = document.getElementsByTagName("*");
	for(var i = 0; i < elmnts.length; i++){
		if(elmnts[i].className == name){
			if(!parent || parent == elmnts[i].parentNode){
				arr.push(elmnts[i]);
			}
		}
	}
	return arr;
}
function LTrim(str){
	var re = /\s*((\S+\s*)*)/;
	return str.replace(re, "$1");
}
function RTrim(str){
	var re = /((\s*\S+)*)\s*/;
	return str.replace(re, "$1");
}
function trim(str){
	return LTrim(RTrim(str));
}
function replaceInvalidBreaks(str){
	var re = /<br(\s\/)?>\s*/gi;
	return str.replace(re, "<br />");
}
function tagsToLowerCase(str){
	return str.replace(/(<\/?[a-z\d]+)([^>]*>)/gi, function($0, $1, $2){
		return ($1.toLowerCase() + $2);
	});	
}
function stripTags(str){
	var re = /<(.|\n)+?>/gi;
	return str.replace(re, "");
}
function clean(str){
	str = trim(str);
	if(str.length > 0){
		str = tagsToLowerCase(str);
		str = replaceInvalidBreaks(str);
	}
	return str;
}
function getTitle(obj){
	var title = "Title";
	var t = obj.parentNode;
	// haz
	var params = obj.getElementsByTagName("param");
	for(var i = 0; i < params.length; i++){
		if(params[i].name == "flashvars"){
			title = params[i].value;
			break;
		}
	}
	return title.substring(title.indexOf("<b>") + 3, title.indexOf("</b>"));
}
function createTextField(id, val, classname){
	var ip = document.createElement("input");
	ip.type = "text";
	ip.id = id;
	ip.value = val;
	ip.className = classname;
	return ip;
}

function addTitleMovie(id, txt){
	var f = new flashObject();
	f.width = "100%";
	f.height = "24";
	f.allowScriptAccess = "sameDomain";
	f.movie = "titles/helvetica.swf";
	f.quality = "high";
	f.scale = "noscale";
	f.salign = "lt";
	f.bgcolor = "#ffffff";
	f.wmode = "transparent";
	f.flashvars = "t=&lt;b&gt;" + txt + "&lt;/b&gt;";
	addFlash(f, "f" + id);
}

function storeForm(cntxt, uid){
	boxForm = document.getElementById("formBox").innerHTML;
	if(cntxt != null){
		context = cntxt;
		if(uid == null){ // not logged in
			build("login", "Please log in first...");
		}
	}
}

function setSelection(){
	clearInterval(sfitv);
	document.getElementById(fieldName).select();
}

function build(screen, msg){
	var ih = "";
//			alert("building " + screen);
	switch(screen){
		case "login":
			//show login screen
			ih = 	"<form name=\"frm\" id=\"frm\" action=\"report.php\" onsubmit=\"return false\">";
			ih +=	"<div class=\"li\">"
			ih +=	"<strong>" + msg + "</strong><br />";
			ih +=	"<input type=\"text\" id=\"login\" name=\"login\" value=\"login\" /><br />";
			ih +=	"<input type=\"text\" id=\"password\" name=\"password\" value=\"password\" />";
			ih +=	"&nbsp;&nbsp;<input type=\"button\" class=\"submit\" value=\"login\" onclick=\"loginSubmit()\" /><br />";
			ih +=	"</div>";
			ih +=	"<div class=\"li\"><strong>Not registered yet?</strong>";
			ih +=	"&nbsp;&nbsp;<input type=\"button\" class=\"submit\" value=\"sign up!\" onclick=\"registerClick()\" />";
			ih +=	"</div>";
			ih +=	"<div class=\"li\"><strong>Forgot your login info?</strong><br />";
			ih +=	"<input type=\"button\" class=\"submit\" value=\"send me my login info!\" onclick=\"loginInfoClick()\" />";
			ih +=	"</div>";
			ih +=	"</form>";
			fieldName = "login";
			sfitv = setInterval(setSelection, 100);
			break;
		case "reportForm":
			// show form for reporting
			var options;
			for(var i = 1; i <= 10; i++){
				sel = "";
				if(i == 6)
					sel = " selected=\"selected\"";
				options += "<option value=\"" + i + "\"" + sel + ">" + i + "</option>";
			}
			ih =	"<div class=\"li\"><strong>" + msg + "</strong><br />";
			ih += 	"<form name=\"frm\" id=\"frm\" action=\"report.php\" onsubmit=\"return false\">";
			ih +=	"<strong>Control of the match:</strong><br />";
			
			ih += 	"<input type=\"text\" id=\"field1\" name=\"field1\" class=\"fields\" value=\"remarks (optional)\" />";
			ih +=	"<select name=\"marks1\" id=\"marks1\" class=\"marks\">";
			ih +=	options + "</select><br />";
			
			ih +=	"<strong>Calls:</strong><br />";
			
			ih += 	"<input type=\"text\" id=\"field2\" name=\"field2\" class=\"fields\" value=\"remarks (optional)\" />";
			ih +=	"<select name=\"marks2\" id=\"marks2\" class=\"marks\">";
			ih +=	options + "</select><br />";
			
			ih +=	"<strong>Neutrality:</strong><br />";
			
			ih += 	"<input type=\"text\" id=\"field3\" name=\"field3\" class=\"fields\" value=\"remarks (optional)\" />";
			ih +=	"<select name=\"marks3\" id=\"marks3\" class=\"marks\">";
			ih +=	options + "</select><br />";
			
			ih +=	"<strong>Style:</strong><br />";
			
			ih += 	"<input type=\"text\" id=\"field4\" name=\"field4\" class=\"fields\" value=\"remarks (optional)\" />";
			ih +=	"<select name=\"marks4\" id=\"marks4\" class=\"marks\">";
			ih +=	options + "</select><br />";
			
			ih +=	"<strong>Overall performance:</strong><br />";
			
			ih += 	"<textarea id=\"field5\" name=\"field5\" class=\"fields\">general remarks (optional)</textarea>";
			
			ih +=	"<input type=\"button\" class=\"submit\" value=\"submit report\" onclick=\"reportSubmit()\" />";
			ih +=	"</form></div>";
			// select first field in form:
			fieldName = "field1";
			sfitv = setInterval(setSelection, 100);
			break;
		case "report":
			// show user's report
			var fNames = ["Control", "Calls", "Neutrality", "Style", "General assessment"];
			csl = msg.split("##");
			var jri = csl.shift(); // jr reporter id
			
			for(var i = 0, j = 0; i < csl.length - 2; i += 2, j++){
				if(j < 4){
					ih += "<div class=\"li\"><div class=\"marks\">" + csl[i + 1] + "</div><strong>" + fNames[j] + ": </strong>" + csl[i] + "</div>";
				}else{
					ih += "<div class=\"header\"><div class=\"marks\">" + csl[i + 1] + "</div>" + fNames[j] + "</div>";
					ih += "<div>" + csl[i] + "&nbsp;</div>";
				}
			}
			if(jri == "0"){
				ih += "<div class=\"header\">Feel inspired to write a full report?</div>";
				ih += "<div><a href=\"your_report_full.php?matchID=" + matchID + "\">Write a full match report for this match</a></div>";
			}else{
				// alert("jr report id = " + jri);	
			}
			break;
		case "regForm":
			// show registration form
			ih =	"<div class=\"li\">";
			ih +=	"<strong>" + msg + "</strong>";
			ih += 	"<form name=\"frm\" id=\"frm\" action=\"report.php\" onsubmit=\"return false\">";
			ih +=	"<input type=\"text\" id=\"name\" name=\"name\" value=\"" + name_text + "\" /><br />";
			ih +=	"<input type=\"email\" id=\"email\" name=\"email\" value=\"" + email_text + "\" />";
			ih +=	"<input type=\"text\" id=\"login\" name=\"login\" value=\"" + login_text + "\" /><br />";
			ih +=	"<input type=\"text\" id=\"password\" name=\"password\" value=\"" + pw_text + "\" />";
			ih +=	"<input type=\"button\" class=\"submit\" value=\"register\" onclick=\"registerSubmit()\" />";
			ih +=	"</form>";
			ih +=	"</div>";
			// select first field in form:
			fieldName = "name";
			sfitv = setInterval(setSelection, 100);
			break;
		case "regConfirm":
			// show confirmation form
			var pv = document.getElementById("password") ? document.getElementById("password").value : "password";
			var lv = document.getElementById("login") ? document.getElementById("login").value : "password";
			
			ih =	"<div class=\"li\">";
			ih +=	"<strong>" + msg + "</strong>";
			ih += 	"<form name=\"frm\" id=\"frm\" action=\"report.php\" onsubmit=\"return false\">";
			ih +=	"<input type=\"text\" id=\"login\" name=\"login\" value=\"" + lv + "\" /><br />";
			ih +=	"<input type=\"text\" id=\"password\" name=\"password\" value=\"" + pv + "\" />";
			ih +=	"<input type=\"text\" id=\"code\" name=\"code\" value=\"confirmation code\" /><br />";
			ih +=	"<input type=\"button\" class=\"submit\" value=\"register\" onclick=\"registerConfirm()\" />";
			ih +=	"</form>";
			ih +=	"</div>";
			// select first field in form:
			fieldName = "login";
			sfitv = setInterval(setSelection, 100);
			break;
		case "sendInfo":
			// show login info form
			ih =	"<div class=\"li\">";
			ih +=	"<strong>" + msg + "</strong>";
			ih += 	"<form name=\"frm\" id=\"frm\" action=\"report.php\" onsubmit=\"return false\">";
			ih +=	"<input type=\"text\" id=\"email\" name=\"email\" value=\"email address\" />";
			ih +=	"&nbsp;&nbsp;<input type=\"button\" class=\"submit\" value=\"ok\" onclick=\"loginInfoSubmit()\" />";
			ih +=	"</form>";
			ih +=	"</div>";
			// select first field in form:
			fieldName = "email";
			sfitv = setInterval(setSelection, 100);
			break;
		case "postForm": // form for forum post
			document.getElementById("postHeader").innerHTML = msg;
			ih =	"<form id=\"msg\" method=\"post\" action=\"forum.php\" onsubmit=\"return false\">";
			ih +=	"<input type=\"hidden\" id=\"forumID\" name=\"fID\" value=\"" + fID + "\" />";
			ih +=	"<div class=\"li\">";
			ih +=	"<input type=\"text\" class=\"title\" id=\"postName\" name=\"postName\" value=\"(your topic title)\" />";
			ih +=	"</div>";
			ih +=	"<div class=\"li\">";
			ih +=	"<textarea id=\"postCopy\" name=\"postCopy\">(your message)</textarea>";
			ih +=	"</div>";
			ih +=	"</form>";
			ih +=	"<div class=\"button\"><a href=\"#\" onclick=\"sendMessage()\">Send</a></div>";
			fieldName = "postName";
			sfitv = setInterval(setSelection, 100);
			break;
		case "showMessage":
			// just show the message returned from the server
			ih =	"<div class=\"li\"><strong>" + msg + "</strong></div>";
			break;
		case "articles":
			// do something extremely intelligent here
			var node_art;
			var div_art;
			var div_art_id;
			var div_art_header;
			var text_art_header;
			var div_art_header_movie;
			var div_art_date;
			var text_art_date;
			var div_art_arr_p;
			var div_art_p;
			var div_art_arr_p;
			if(!msg.length)msg = msg.parentNode.childNodes;
			for(var i = 0; i < msg.length; i++){
				node_art  = msg[i];
				div_art_id = "art" + node_art.getAttribute("id");
//				document.getElementById("copy").removeChild(document.getElementById(div_art_id));
				div_art = document.createElement("div");
				div_art.id = div_art_id;
				div_art.className = "article";
				div_art.onclick = function(){
					makeEditable(this);	
				}
				div_art_header = document.createElement("div");
				div_art_header.className = "title";
				div_art_header_movie = document.createElement("div");
				div_art_header_movie.id = "f" + node_art.getAttribute("id");
				div_art_header.appendChild(div_art_header_movie);
				div_art.appendChild(div_art_header);
				
				div_art_date = document.createElement("em");
				text_art_date = document.createTextNode(node_art.getAttribute("dateStory"));
				div_art_date.appendChild(text_art_date);
				div_art.appendChild(div_art_date);
				
				div_art_arr_p = node_art.firstChild.nodeValue.split("##");
				for(var j = 0; j < div_art_arr_p.length; j++){
					div_art_p = document.createElement("p");
					if(j == 0) div_art_p.className = "p_intro";
					div_art_p.innerHTML = div_art_arr_p[j];
					div_art.appendChild(div_art_p);
				}
				
				document.getElementById("art0").parentNode.insertBefore(div_art, document.getElementById("art0"));
				document.getElementById("art0").parentNode.insertBefore(document.getElementById("art0"), div_art);
				
				text_art_header =  node_art.getAttribute("textHead");
				setTimeout(addTitleMovie, 100, node_art.getAttribute("id"), text_art_header);
			}
			return;
		case "matches":
			var node_match;
			var div_match;
			var h2;
			var txt;
			var plh = document.getElementById("plh_matches");
			var plhcl = plh.childNodes.length;
			var em;
			var strong;
			var br;
			var a
			for(var i = 0; i < plhcl; i++){
				plh.removeChild(plh.childNodes[0]);
			}
			if(!msg.length)msg = msg.parentNode.childNodes;
			for(var i = 0; i < msg.length; i++){
//				console.log(i);
				node_match  					= msg[i];
				var div_match 				= document.createElement("div");
				div_match.className 	= "match";
				div_match.refID 			= node_match.getAttribute("refID");
				div_match.matchID 		= node_match.getAttribute("gameID");
				div_match.onmouseover = function(){this.style.backgroundColor = "#E6FEEC";};
				div_match.onmouseout 	= function(){this.style.backgroundColor = "";};
				div_match.onclick 		= function(){location.href = "match.php?refID=" + this.refID + "&matchID=" + this.matchID;};
				txt 									= document.createTextNode(node_match.getAttribute("textHead"));
				h2 										= document.createElement("h2");
				h2.appendChild(txt);
				
				div_match.appendChild(h2);
				em = document.createElement("em");
				txt = document.createTextNode(node_match.getAttribute("teamHome") + " - " + node_match.getAttribute("teamAway") + " (" + node_match.getAttribute("score") + ") " + node_match.getAttribute("dateGame") + " ");
				em.appendChild(txt);
				strong = document.createElement("strong");
				txt =  document.createTextNode(node_match.getAttribute("refName"));
				strong.appendChild(txt);
				em.appendChild(strong);
				div_match.appendChild(em);
				br = document.createElement("br");
				div_match.appendChild(br);
				strong = document.createElement("strong");
				txt = document.createTextNode(stripTags(node_match.firstChild.nodeValue));
				strong.appendChild(txt)
				div_match.appendChild(strong);
				em = document.createElement("em");
				txt = document.createTextNode(" (" + node_match.getAttribute("reporter") + ") ");
				em.appendChild(txt);
				div_match.appendChild(em);
				/*
				a = document.createElement("a");
				a.href = "#";
				txt = document.createTextNode("Read more >");
				a.appendChild(txt);
				div_match.appendChild(a);
				*/
				plh.appendChild(div_match);
			}
			return;
			
		case "refs":
			s = document.getElementById("ref_sel");
			setOptions(s, msg, "referee");
			s.onchange = gotoRefPage;
			return;
			
		case "countries":
			s = document.getElementById("country_sel");
			setOptions(s, msg, "country");
			s.onchange = gotoCountryPage;
			return;
			
		case "refBox":
			
			var txt;
			
			var refBox = document.createElement("div"); // just a container
			refBox.className = "specs";
			
			var boxHeader = document.createElement("div");
			boxHeader.className = "headerTop";
			boxHeader.style.overflow = "hidden";
			txt = document.createTextNode(msg.getAttribute("leagueName"));
			boxHeader.appendChild(txt);
			
			refBox.appendChild(boxHeader);
			
			msg = msg.childNodes;
			
			var spec, marks, a;			
			for(var i = 0; i < msg.length; i++){
				
				spec = document.createElement("div");
				spec.className = "spec";
						
				marks = document.createElement("div");
				marks.className = "marks";
				txt = document.createTextNode(msg[i].getAttribute("score"));
				marks.appendChild(txt);
				spec.appendChild(marks);

				a = document.createElement("a");
				a.href = "http://www.worldreferee.com/site/copy.php?linkID=" + msg[i].getAttribute("id") + "&linkType=referee&contextType=bio";
				txt = document.createTextNode(msg[i].getAttribute("name"));
				a.appendChild(txt);
				spec.appendChild(a);
				
				refBox.appendChild(spec);
				
			}
			
			var plh = document.getElementById("col1"); // <!-- more generic would be nice
			plh.appendChild(refBox);
			
			return;

		case "matchline":
			var data = msg.split("##");
			ih =	"<a class=\"li\" href=\"#\" onclick=\"setMatch(" + data[0] + ")\">" + data[1] + "</a><br />";
			break;
		case "matchlines":
			var data = msg.split("##");
			ih =	"<a class=\"li\" href=\"#\" onclick=\"setMatch(" + data[0] + ")\">" + data[1] + "</a><br />";
			break;
		case "loadMatches":
			result = msg.getElementsByTagName('match');	
			var ih;
			var mtch;
			for(var i = 0; i < result.length; i++){
				mtch = result[i];
				ih +=	"<a class=\"li\" href=\"#\" onclick=\"getGame(" + mtch.getAttribute("id") + ")\">" + mtch.getAttribute("name") + "</a><br />";
			}
			break;
			
		default:
			ih = boxForm;
			
	}
	
// console.log("context " + context + " screen " + screen)

	if(context != "standard login"){
		if(context == "matches"){
			if(screen == "loadMatches"){
				document.getElementById("match_list").innerHTML = ih + "\n";
			}else{
				document.getElementById("log").innerHTML += ih + "\n";
			}
		}else{
			document.getElementById("formBox").innerHTML = ih;
		}
	}else{
		document.getElementById("loginBox").innerHTML = ih;
	}
	
}

function getRefBoxes(arr){
	for(var i = 0; i < arr.length; i++){
		doRequest("getRefBox&leagueID=" + arr[i]);
	}	
}

function setOptions(s, msg, subject){
	var t, m;
	s.options[0] = new Option("Select " + subject, "");
	for(var i = 0; i < msg.length; i++){
		m = msg[i];
		t = m.firstChild.nodeValue;
		s.options[i + 1] = new Option(t, m.getAttribute("value"));
	}
}

function gotoCountryPage(){
	location.href = "http://www.worldreferee.com/site/country.php?countryID=" + this.options[this.options.selectedIndex].value;
}

function gotoRefPage(){
	location.href = "http://www.worldreferee.com/site/copy.php?linkType=referee&contextType=bio&linkID=" + this.options[this.options.selectedIndex].value;
}

// click on 'your report' tab
function yourReportClick(mID, rID){
	matchID = mID;
	if(matchID == "")return;
	context = "your report";
	refID = rID;
	doRequest("getReport&matchID=" + matchID);
}

var max = 0;
function branchResult(){
// console.log("response: " + http.readyState + ") " + http.responseText + " > " + http.responseXML);
	if (http.readyState == 4){
		var xmlTree = http.responseXML;
		var result;
		var name;
		var value;
		var status;
		if(xmlTree){
			
			result = xmlTree.documentElement ? xmlTree.documentElement : xmlTree.firstChild;
			if(result.nodeName == "parsererror"){
				console.log("result " + result.nodeName + " " + result.childNodes[0].nodeValue);			
			}
			if(result && result.nodeName == "xml") result = xmlTree.childNodes[1];// ie weirdness
		}
// console.log(http.readyState + " " + http.responseXML);
// console.log("responseText: " + http.responseText);
// console.log("xmlTree: " + xmlTree);
// console.log("result: " + result);
		if(xmlTree && result){
			name 		= result.getAttribute("name");
			value 	= result.getAttribute("value");
			status 	= result.getAttribute("status");
			if(value == null){
				value = result.childNodes.length > 1 ? result.childNodes : result.firstChild.nodeType == 1 ? result.firstChild : result.firstChild.nodeValue;
			}
//			console.log("result: " + http.readyState + ") " + name + " >> " + value + " >> " + status);
			switch(name){
				case "adClick":
					if(value != ""){
//						location.href = value;
						window.open(value, "ad");
//						location.replace(value);
					}
					break;
				case "login":
					switch(value){
						case "user logged in":
							if(context == "new topic"){
								build("postForm", "Welcome. Please start your new topic");
							}else if(context == "reply to post"){
								build("reply to post form", ""); // default: print saved form
								document.getElementById("postHeader").innerHTML = "Welcome. Now you can reply to this post:";
							}else if(context == "standard login"){
								showWelcome(result.firstChild.nodeValue);
							}else{//show report form
								processing = false;
								yourReportClick(matchID, refID);
							}
							break;
						case "account activated":
							if(context == "new topic"){
								build("postForm", "Welcome. Please start your new topic");
							}else if(context == "reply to post"){
								build("reply to post form", ""); // default: print saved form
								document.getElementById("postHeader").innerHTML = "Welcome. Now you can reply to this post:";
							}else if(context == "standard login"){
								showWelcome();
							}else{
								build("reportForm", "Welcome. Your account was successfully activated. Now please give us your marks...");
							}
							break;
						case "Login or Password is incorrect":
							build("login", value);
							break;
						case "not activated":
							build("regConfirm", "You need to activate your account first. Check your email for the confirmation code...");
							break;
						default:
							build("showMessage", status + ": " + value);
					}
					break;
				case "report":
					switch(value){
						case "not logged in":
							//show login screen
							build("login", "Please log in first");
							break;
						case "no report found":
							//show report form
							build("reportForm", "Please fill out your report");
							break;
						default:
							// show report
							if(status == "OK"){
								if(!value || value == "") value = 0;
								csl = value + "##"; // prepend rep id
								result = xmlTree.getElementsByTagName('field');
								for(var i = 0; i < result.length; i++){
									csl += result[i].getAttribute("remarks") + "##";
									csl += result[i].getAttribute("marks") + "##";
								}
								// csl = csl.substring(0, csl.length - 2);
								build("report", csl);
								umitv = setInterval(updateMarks, 100);
							}else{
								build("showMessage", status + ": " + value);
							}
					}
					break;
				case "register":
					switch(value){
						case "You are already registered":
							// fall through
						case "Sorry, this nickname is taken":
							//show login screen
							build("regForm", value);
//							build("login", value);
							break;
						case "confirm registration":
							build("regConfirm", "You were successfully registered. Please login and activate your account by entering the confirmation code that was sent to you.");
							break;
						default:
							build("showMessage", status + ": " + value);
					}
					break;
				case "login info":
					switch(value){
						case "login info sent":
							build("login", "Your login info has been sent to your mail box. Please log in.<br />");
							break;
						case "login info not sent":
							build("sendInfo", "Something went wrong while sending your login info. Please check your email address and try again.");
							break;
						default:
							build("showMessage", status + ": " + value);
					}
					break;
				case "marks":
					if(status == "OK"){
						showMarks(value);
					}else{
						build("showMessage", status + ": " + value);
					}
					break;
				case "junior report":
					if(status == "OK"){
						showJuniorReportCopy(value);
					}else{
						build("showMessage", status + ": " + value);
					}
					break;
				case "update article":
					// do nothing
					break;
				case "articles":
					if(status == "OK"){
						build("articles", value);
					}else{
						build("showMessage", status + ": " + value);
					}
					break;
				case "matches":
					if(status == "OK"){
						build("matches", value);
					}else{
						build("showMessage", status + ": " + value);
					}
					break;
				case "keptAlive":
					// do nothing
					break;
				case "refs":
					build("refs", value);
					break;
				case "countries":
					build("countries", value);
					break;
				case "refBox":
					build("refBox", result);
					break;
				case "profileReports":
					var plh = document.getElementById("ur");
					plh.innerHTML = value;
					showFirstReport();					
					break;
				case "profileMatch":
					var reporter 	= result.getAttribute("reporter");
					var body 			= getValue(result.getElementsByTagName("body")[0]);
					var matchline = getValue(result.getElementsByTagName("matchline")[0]);
					var marks 		= result.getElementsByTagName("mark");
					var arr_copy 	= body.split("##");
					addFlashTitle(arr_copy.shift(), "copy_title");
					addReportCopy(arr_copy, "copy_body");
					for(var i = 0; i < marks.length; i++){
						document.getElementById("mark" 		+ (i + 1)).innerHTML 	= marks[i].getAttribute("value");
						document.getElementById("comment" + (i + 1)).innerHTML 	= getValue(marks[i]);
					}
					document.getElementById("matchline").innerHTML = matchline;
					document.getElementById("reporterName").innerHTML = reporter;
					break;
				case "gotoLivePage":
					location.href = "/site/match.php?matchID=" + value;
					break;
				case "data_venues_and_towns":
					setVenueAndTownData(result.firstChild);
					break;
				case "data_leagues":
// console.log("responseText: " + http.responseText);
					setLeagueData(result.firstChild);
					break;
				case "data_teams_and_venues":
					setTeamAndVenueData(result.firstChild);
					break;
				case "insertOK":
					// no action
					var l = Dom.el("log");
					if(l){
						l.innerHTML += value + ": " + result.getAttribute("id");
					}
					console.log("sql executed = " + value + ": " + result.getAttribute("id"));
					break;
				case "data_referees":
					setRefereeData(result.firstChild);
					break;
				case "addMatch":
					var matchID = result.getAttribute("id");
					storeMatch(matchID);
					build("matchline", matchID + "##" + matchID + " | " + name + " " + status + ": " + value);
					break
				case "updateMatch":
					var matchID = result.getAttribute("id");
					build("matchline", matchID + "##" + matchID + " | " + name + " " + status + ": " + value);
					break
				case "getGame":
					loadMatch(result.getAttribute("id"), value);
					break;
				case "loadMatches":
					build("loadMatches", result);
					break;
				default:
					build("showMessage", status + ": " + value);
			}
		}else{
			setTimeout(branchResult, 100);
	//		alert("error. please report this to our adminstrators. thanks. " + http.readyState);
		}
		processing = false;
	}
}

// returns the value of a node
function getValue(node){
	return node.firstChild.nodeValue;
}

var reportSubmitted = 0;
function reportSubmit(){
	if(reportSubmitted != matchID){ // <-- check if we do not have a report for this match already
		var varstr = "submitReport&refereeID=" + refID + "&matchID=" + matchID;
		var f, m;
		for(var i = 1; i <= 5; i++){
			f = document.getElementById("field" + i).value;
			f = (f.indexOf("(optional)") > - 1) ? "" : f;
			varstr += "&field" + i + "=" + f;
			if(i < 5){
				m = document.getElementById("marks" + i);
				m = m.options[m.options.selectedIndex].value;
				varstr += "&marks" + i + "=" + m;
			}
		}
		doRequest(varstr);
		reportSubmitted = matchID;
	}
}

function loginSubmit(cntxt, id){
	var l, p;
	l = document.getElementById("login").value;
	p = document.getElementById("password").value;
	if(l == "" || p == "" || l == "login" || p == "password"){
		build("login", "Your input is not correct. Try again...");
	}else{
		if(cntxt != null){
			context = cntxt;
			if(context == "new topic"){
				fID = id;
			}
		}
		doRequest("login&login=" + document.getElementById("login").value + "&password=" + document.getElementById("password").value);
	}
}

function registerClick(){
	// show register screen
	build("regForm", "Sign up now!");
}

function registerSubmit(){
	var l, p, e, n
	l = document.getElementById("login").value;
	p = document.getElementById("password").value;
	e = document.getElementById("email").value;
	n = document.getElementById("name").value;
	if(l == "" || p == "" || e == "" || n == "" || !isEmail(e) || l == login_text || p == pw_text || n.indexOf(name_text) > -1){
		build("regForm", "Your input is not correct. Try again...");
	}else{
		doRequest("register&login=" + l + "&password=" + p + "&email=" + e + "&name=" + n);
	}
}

function registerConfirm(){
	var l, p, c;
	l = document.getElementById("login").value;
	p = document.getElementById("password").value;
	c = document.getElementById("code").value;
	if(l == "" || p == "" || c == ""){
		build("regConfirm", "Your input is not correct. Try again...");
	}else{
		doRequest("activate&login=" + l + "&password=" + p + "&code=" + c);
	}
}

function loginInfoClick(){
	build("sendInfo", "Please enter your email address and we will send you your login info");
}

function loginInfoSubmit(){
	var e;
	e = document.getElementById("email").value;
	if(e == "" || !isEmail(e)){
		build("sendInfo", "Your input is not correct. Try again...");
	}else{
		doRequest("sendInfo&email=" + e);
	}
}

function updateMarks(){
	clearInterval(umitv);
	doRequest("getMarks&refID=" + refID + "&matchID=" + matchID);
}

function showMarks(mrks){
	var arr_mrks = mrks.split(";");
	for(var i = 0; i <= 3; i++){
		document.getElementById("mrks" + i).innerHTML = arr_mrks[i];
	}
}
		
function getJuniorReportCopy(juniorReporterID, matchID){
//	alert("getting full report for " + juniorReporterID + ", "  + matchID);
	if(juniorReporterID){
		doRequest("getJuniorReportCopy&reporterID=" + juniorReporterID + "&matchID=" + matchID);
	}
}

function addFlashTitle(title, plh_id){
	document.getElementById(plh_id).innerHTML = "<div id=\"f2\"></div>";
	var f = new flashObject();
	f.width = "100%";
	f.height = "24";
	f.allowScriptAccess = "sameDomain";
	f.movie = "titles/helvetica.swf";
	f.quality = "high";
	f.scale = "noscale";
	f.salign = "lt";
	f.bgcolor = "#ffffff";
	f.wmode = "transparent";
	f.flashvars = "t=&lt;b&gt;" + title + "&lt;/b&gt;"
	addFlash(f, "f2");
}

function addReportCopy(arr_copy, plh_id){
	document.getElementById(plh_id).innerHTML = "";
	if(arr_copy && arr_copy.length > 1 && arr_copy[0] != ""){
		var txt;
		var copy = "<p><strong>" + arr_copy[0] + "</strong></p>\n";
		for(var i = 1; i <= arr_copy.length - 1; i++){
			txt = arr_copy[i]
			if(txt && txt != ""){
				copy += "<p><strong>" + txt + "</strong><br />\n";
				i++;
				txt = arr_copy[i];
				if(txt && txt != ""){
					copy +=	arr_copy[i] + "</p>\n";
				}
			}
		}
		document.getElementById(plh_id).innerHTML = copy;
	}else{
		document.getElementById(plh_id).innerHTML = "(No report for this match)";
	}
}

function showJuniorReportCopy(cp){

	var arr_copy = cp.split("##");
	// arr_copy.pop(); // string ends with delimiter so last item will be undefined
	
	var title = arr_copy.shift();
	
	addFlashTitle(title, "copy_title");

	addReportCopy(arr_copy, "copy_body");

	if(document.getElementById("reporterName"))
		document.getElementById("reporterName").style.visibility = "hidden";
}

function isEmail(str){
	regexp = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[\w-\.]*[a-zA-Z0-9]\.[a-zA-Z]{2,7}$/;
	return regexp.exec(str)
}

function fillSearchBoxOptions(){
	doRequest("getRefs");
	doRequest("getCountries");
}
function fillCountriesOptions(){
	doRequest("getCountries");	
}
//ajax
var url = "/site/ajax.php";
var processing = false;

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
	try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
		xmlhttp = false;
	  }
	}
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	try {
	  xmlhttp = new XMLHttpRequest();
	  xmlhttp.overrideMimeType("text/xml"); 
	} catch (e) {
	  xmlhttp = false;
	}
  }
  return xmlhttp;
}
var http = getHTTPObject();

function doRequest(req){
//	alert(url + "?request=" + req + "&page=" + location.href);
	if(http){
		if(!processing){
			http.open("POST", url + "?request=" + req + "&page=" + location.href, true);
			http.onreadystatechange = branchResult;
			processing = true;
			http.send(null);
		}else{
			setTimeout(doRequest, 500, req);
		}
	}
}

/* footer login */		
function showLogin(el){
	context = "standard login";
	var d = document.getElementById("loginBox");
	var d2;
	if(!d){
		d = document.createElement("div");
		d.className = "col3";
		with(d.style){
			position = "absolute";
			zIndex = 2;
			backgroundColor = "#fff";
		}
		var dims = getWinDim();
		d2 = document.createElement("div");
		d2.className = "box";
		d2.id = "loginBox";
		d.appendChild(d2);
		d2.style.margin = 0;
		document.body.appendChild(d);
		d.style.left = ((dims.w / 2) - (d.offsetWidth / 2)) + "px";
		d.style.top = ((dims.h / 2) - (d.offsetHeight / 2)) + "px";
	}
	build("login", "Please login");
}

function showWelcome(userData){
	var welcomeText = "Welcome. Thanks for logging in. <a href=\"#\" onclick=\"this.parentNode.parentNode.parentNode.style.display = 'none'\">close</a>";
	build("showMessage", welcomeText);
	if(userData){
		var ud = userData.split("##");
		var ur = ud[0];
		var un = ud[1];
		var cp = location.href; // current page
		var ep = cp.indexOf("match.php") > -1 ? "matchReport" : cp.indexOf("copy.php") > -1 ? "copy2" : ""; // edit page /publish/copy2.php?linkID=494&amp;linkType=referee&amp;contextType=bio
		if(
		   cp != "" && 
		   !document.getElementById("edit_button") && 
		   (ur == "senior reporter" || (ur == "matchreporter" && (author == "" || un == author)) || ur == "editor" || ur == "administrator")
		){
			// show edit button	
			var eb = document.createElement("span");
			eb.id = eb.className = "edit_button";
			eb.url = "/publish/" + ep + ".php" + cp.substring(cp.indexOf("?"), cp.length);
			eb.onclick = function(){
				if(this.url.indexOf("home") < 0 && this.url.indexOf("/.") < 0){
					location.replace(this.url)
				}else{ 
					location.replace("/?request=edit");
				}
			}
			eb.appendChild(document.createTextNode("edit"));
			getElementsByClassName("tabs")[0].appendChild(eb);
		}
	}
}
function keepAlive(){

	doRequest("showNXS");

}

/* test */
function adClick(q){
	var req = "adClick&amp;" + q;
	doRequest(req);
	return false;
}

// document.onmousedown = dmd;
document.onmouseup = dmu;
function dmu(e){
	var evt = e ? e : event;
	var trgt = evt.target ? evt.target : evt.srcElement;
	if(trgt.tagName.toLowerCase() == "textarea" || (trgt.tagName.toLowerCase() == "input" && trgt.type == "text")){
		
		trgt.select();
		
	}
}
function dmd(e){
	var evt = e ? e : event;
	var trgt = evt.target ? evt.target : evt.srcElement;
	if(trgt.tagName.toLowerCase() == "textarea" || (trgt.tagName.toLowerCase() == "input" && trgt.type == "text")){
		
		if(trgt.value != "" && trgt.value.length < 20){
			
			trgt.org_value = trgt.value;
			trgt.value = "";
			trgt.onblur = input_blur;
		
		}
		
	}
}
function input_blur(){

	if(this.value == ""){
	
		this.value = this.org_value;
	
	}
	this.onblur = null;

}

/* profile */
function getProfileReports(year, uid){
	doRequest("profileReports&y=" + year + "&u=" + uid);
}

function getProfileMatch(uid, matchID){
	doRequest("profileMatch&m=" + matchID + "&u=" + uid);
}

function profileReports(year, uid){
	getProfileReports(year, uid);
	document.getElementById("yr").innerHTML = year;
}

function showFirstReport(){
	var plh = document.getElementById("ur");
	var tr = plh.getElementsByTagName("tr")[0];
	if(tr){
		if(tr.onclick){
			tr.onclick();
		}else if(tr.click){
			tr.click();
		}
	}
}

function unLockMatchAndGoToLivePage(matchID, userID){
	doRequest("unlockMatch&m=" + matchID + "&u=" + userID);
}

/* data: venues */
function getVenueData(countryId){
	doRequest("dataVenues&c=" + countryId);
}

function setVenueData(data){
	var venue_options = data.getElementsByTagName("venues")[0].firstChild.nodeValue;
	document.getElementById("sel_venues").innerHTML = "<option value=\"0\">Browse venues</option>" + venue_options;
}

function setTownData(data){
	var town_options = data.getElementsByTagName("towns")[0].firstChild.nodeValue;
	document.getElementById("sel_towns").innerHTML = "<option value=\"0\">Select town</option>" + town_options;
}

function setVenueAndTownData(data){
	setVenueData(data);
	setTownData(data);
}

/* data: leagues*/
function getLeagueData(associationId){
	doRequest("dataLeagues&a=" + associationId);
}

function setLeagueData(data){
//	console.log("data " + data.nodeName);
	var league_options = data.getElementsByTagName("leagues")[0].firstChild.nodeValue;
	document.getElementById("sel_leagues").innerHTML = "<option value=\"0\">Browse leagues</option>" + league_options;
}

/* data: teams */
function getTeamData(countryId){
	doRequest("dataTeams&c=" + countryId);
}

function setTeamData(data){
//	console.log("data " + data.nodeName);
	var team_options = data.getElementsByTagName("teams")[0].firstChild.nodeValue;
	document.getElementById("sel_teams").innerHTML = "<option value=\"0\">Browse teams</option>" + team_options;
}

function setTeamAndVenueData(data){
//	console.log("data " + data.nodeName);
	setTeamData(data);
	setVenueData(data);
}

function getTeamAndVenueData(countryId){
	doRequest("dataTeamsAndVenues&c=" + countryId);
}

/* data: referees */
function setRefereeData(data){
	var referee_options = data.getElementsByTagName("referees")[0].firstChild.nodeValue;
	document.getElementById("sel_referees").innerHTML = "<option value=\"0\">Browse referees</option>" + referee_options;
}

function getRefereeData(countryId){
	doRequest("dataReferees&c=" + countryId);
}

/* data: matches */
	
/* globals */
var matchArchive = function(){};
var matchData = function(){};
var md; // current matchData

/* utils */
// gets current value of drop down box
function dd_value(dd_id){
	var val = "NOT FOUND: " + dd_id;
	var dd = document.getElementById(dd_id);
	if(dd)
		val = dd.options[dd.options.selectedIndex].value;
	if(val == "?" || val == " ") val = "";
	return val;
}

// sets drop down to supplied value
function dd_set(dd_id, val){
	val = !(val == "" || val == "?" || val == " ") ? parseInt(val) : "?";
	var dd = document.getElementById(dd_id);
	var dd_options = dd.options;
	for(var i = 0; i < dd_options.length; i++){
		if(dd_options[i].value  == val){
			dd.selectedIndex = i;
			break;
		}
	}
	
}

// checks if minimum amount of data was supplied
function checkInput(task){

	var str_err = "";
	if(task == "update" && document.getElementById("matchID").value == ""){
		str_err += "no match selected to update\n";
	}
	if(dd_value("league") == "" || dd_value("league") == "?"){
		str_err += "league not set\n";
	}
	if(dd_value("venue") == "" || dd_value("venue") == "?"){
		str_err += "venue not set\n";
	}
	if(dd_value("teamHome") == "" || dd_value("teamHome") == "?"){
		str_err += "home team not set\n";
	}
	if(dd_value("teamAway") == "" || dd_value("teamAway") == "?"){
		str_err += "away team not set\n";
	}
	return str_err;
	
}

// adds match to db
function addMatch(){
	
	var str_err = checkInput("add");
	if(str_err.length > 0){
		str_err = "missing data:\n" + str_err;
		alert(str_err);
	}else{
		processMatch("add");
	}
	return false;
	
}

// updates match in db
function updateMatch(){

	var str_err = checkInput("update");
	if(str_err.length > 0){
		str_err = "missing data:\n" + str_err;
		alert(str_err);
	}else{
		processMatch("update");
	}
	return false;
	
}

// stores form data in match data object
// constructs a query
// sends query to php script/ db
// called by addMatch and updateMatch
function processMatch(task){
	
	var dateGame = dd_value("year") + "-" + dd_value("month") + "-" +  dd_value("day");
	var score = dd_value("score1") + "-" + dd_value("score2");
	
	if(task == "add"){
		md = new matchData();
	}else{
		md = matchArchive["slot" + document.getElementById("matchID").value];
	}
	
	md.a = dd_value("referee");
	md.b = dd_value("league");
	md.c = dd_value("teamHome");
	md.d = dd_value("teamAway");
	md.e = dd_value("venue");
	md.f = dd_value("stage");
	md.g = dateGame;
	md.h = score;
	md.i = dd_value("yellowHome");
	md.j = dd_value("yellowAway");
	md.k = dd_value("redHome");
	md.l = dd_value("redAway");
	md.m = dd_value("penaltyHome");
	md.n = dd_value("penaltyAway");
	
	var req 	 = task + "Match";
	req 		+= "&a=" + md.a;
	req 		+= "&b=" + md.b;
	req 		+= "&c=" + md.c;
	req 		+= "&d=" + md.d;
	req 		+= "&e=" + md.e;
	req 		+= "&f=" + md.f;
	req 		+= "&g=" + md.g;
	req 		+= "&h=" + md.h;
	req 		+= "&i=" + md.i;
	req 		+= "&j=" + md.j;
	req 		+= "&k=" + md.k;
	req 		+= "&l=" + md.l;
	req 		+= "&m=" + md.m;
	req 		+= "&n=" + md.n;
	req 		+= "&o=" + document.getElementById("matchID").value;
	
	doRequest(req);
	
}

/* return script: processes data returned by php/mysql */

// called from ajax.js when data was added to db. stores (data preserved in) current md object in archive
// match data object (md) is stored only now because we need the match id from the db
function storeMatch(id){

	matchArchive["slot" + id] = md;
	document.getElementById("matchID").value = id;
	
}

// fills form with data from match data object (with supplied match id)
// called by click on match line in list
function setMatch(id){
	md = matchArchive['slot' + id];
	dd_set("referee", md.a);
	dd_set("league", md.b);
	dd_set("teamHome", md.c);
	dd_set("teamAway", md.d);
	dd_set("venue", md.e);
	dd_set("stage", md.f);
	
	var dte = md.g.split("-");
	dd_set("year", dte[0]);
	dd_set("month", dte[1]);
	dd_set("day", dte[2]);
	
	if(md.h == "-" || md.h == " - " || md.h == "? - ?") md.h = "?-?";
	var scr = md.h.split("-");
	dd_set("score1", scr[0]);
	dd_set("score2", scr[1]);
	
	dd_set("yellowHome", md.i);
	dd_set("yellowAway", md.j);
	dd_set("redHome", md.k);
	dd_set("redAway", md.l);
	dd_set("penaltyHome", md.m);
	dd_set("penaltyAway", md.n);
	document.getElementById("matchID").value = id;
}

// read ## separated list here
// create md
// read md to fill form
function loadMatch(id, str_data){
	md = matchArchive["slot" + id];
	if(!md){
		md = new matchData();
		storeMatch(id);
	}
	var arr_data = str_data.split("##");
	md.a = arr_data[0];
	md.b = arr_data[1];
	md.c = arr_data[2];
	md.d = arr_data[3];
	md.e = arr_data[4];
	md.f = arr_data[5];
	md.g = arr_data[6];
	md.h = arr_data[7];
	md.i = arr_data[8];
	md.j = arr_data[9];
	md.k = arr_data[10];
	md.l = arr_data[11];
	md.m = arr_data[12];
	md.n = arr_data[13];
	setMatch(id);
}

// loads a number of matches from the database
function loadMatches(){
	doRequest("loadMatches");
}

// gets a match from db
function getGame(id){
	doRequest("getGame&matchID=" + id);
}

/* gen form functions */
var Dom = {};
Dom.addClass = function(el, className){
	el = Dom.el(el);

	El.removeClass(el, className)
	el.className = el.className.length > 0 ? el.className + " " + className : className;
}

Dom.removeClass = function(el, className){
	el = Dom.el(el);
	var classes = el.className.split(" ");
	var str_class = "";
	for(var i = 0; i < classes.length; i++){
		if(classes[i] != "" && classes[i] != className){
			str_class += " " + classes[i];
		}
	}
	el.className = str_class.substr(1);
}

Dom.el = function(el){
		
	if(typeof el == "string"){
		el = document.getElementById(el);
	}
	
	return el;
}

var Form = {
	EMAIL	: "EMAIL",
	DATE	: "DATE"
};

Form.value = function(el){
	
	el = Dom.el(el);
	
	var isInput 		= (el instanceof HTMLInputElement);
	var isSelect 		= (el instanceof HTMLSelectElement);
	var isTextArea 	= (el instanceof HTMLTextAreaElement);
	
	var val = "this form element not supported";
	if(isInput || isTextArea){
		val = el.value;
	}else if(isSelect){
		val = el.options[el.options.selectedIndex].value;
	}

	return val;

}

Form.isDate = function(el){
	el = Dom.el(el);
	val = Form.value(el);
	regexp = /^\d{4}-\d{2}-\d{2}$/;
	var ret = regexp.exec(val);
	return ret;
}

Form.isEmail = function(el){
	el = Dom.el(el);
	val = Form.value(el);
	regexp = /^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[\w-\.]*[a-zA-Z0-9]\.[a-zA-Z]{2,7}$/;
	return regexp.exec(val)
}

Form.blur = function(el){
	el = Dom.el(el);
	el.blur();
}

Form.focus = function(el){
	el = Dom.el(el);
	el.focus();
}
/*
params: 						params object:
params.no: 					array of disallowed values
params.yes					array of allowed values
params.errorClass: 	class to add to element on error
TODO:								check INT, NAN, ZIP, EMAIL, NUMBER etc
*/

Form.check = function(el, params){
	
	el = Dom.el(el);
	
	if(!params) params = {};
	var checks 			= params.checks ? params.checks : [];
	var no 					= params.no 		? params.no 		: [];
	var yes 				= params.yes 		? params.yes 		: [];	
	var errorClass 	= params.errorClass;
	var val 				= Form.value(el);
	var i;

	el.focus();
	
	for(i = 0; i < checks.length; i++){
		switch(check){
			case Form.DATE:
				if(!Form.isDate(el)){
					return false;
				}
				break;
			case Form.EMAIL:
				if(!Form.isEmail(val)){
					return false;
				}
				break;
		}
	}
	
	// first check for allowed values
	for(i = 0; i < yes.length; i++){
		if(val == yes[i]){
			el.blur();
			return true;
		}
	}	
	
	if(yes.length > 0){
		return false;
	}

	// check for disallowed values
	no.push("");
	for(i = 0; i < no.length; i++){
		if(val == no[i]){
			return false;
		}
	}
	
	el.blur();
	return true;

}























