// JavaScript Document
var userRole;

function getStaticContent()
{
	getContent("userinfo=1");
}

function printStaticPage(role)
{
	userRole = role;
	getContent("browser="+navigator.appCodeName+"&browserName="+navigator.appName+"&browserVersion="+navigator.appVersion+"&browserMinorVersion="+navigator.appMinorVersion+"&os="+navigator.platform+"&width="+screen.width+"&height="+screen.height);
	getStaticContent();
}

function getModifiedMembers(elements)
{
	var i=0;
	var params = "";
    while (elements[i] != undefined)
	{
		if (elements[i].name == 'inforow' && elements[i+1].value == 'true')
		{
			params = params+"&player"+i+"=";
			params = params+"<id>"+elements[i+1].id+"</id>";
			params = params+"<number>"+elements[i+2].value+"</number>";
			params = params+"<firstname>"+elements[i+3].value+"</firstname>";
			params = params+"<lastname>"+elements[i+4].value+"</lastname>";
			params = params+"<street>"+elements[i+5].value+"</street>";
			params = params+"<zipcode>"+elements[i+6].value+"</zipcode>";
			params = params+"<city>"+elements[i+7].value+"</city>";
			params = params+"<telephone>"+elements[i+8].value+"</telephone>";
			params = params+"<email>"+elements[i+9].value+"</email>";
			params = params+"<relation>"+elements[i+10].value+"</relation>";
			params = params+"<role>"+elements[i+11].value+"</role>";
		}
		i = i+12;
	}
	return(params);
}

function savePage(page,type,evalFunction)
{
	elements = page.elements;
    params = "page="+type;
	if (page.id == "modifyform")
	{
	    params = params + getModifiedMembers(elements);
	}
	else
	{
	    for (i=0 ; i < elements.length ; i++)
	    {
			if (elements[i].disabled == false) {
			    if (elements[i].type == 'checkbox')
			    {
				    value = elements[i].checked;
		    	}
			    else if (elements[i].type == 'select-one' && elements[i].selectedIndex >= 0)
			    {//alert(elements[i].selectedIndex);
				    opts = elements[i].options;
				    value = opts[elements[i].selectedIndex].value;
			    }
				else if (elements[i].type == 'radio')
				{
					if (elements[i].checked)
						value = elements[i].value;
					else
						value = "false";
				}
		    	else
			    	value = elements[i].value;//alert(elements[i].id+"  "+value);
				if (value == "+")
					value = "\%2B";
			    params = params+"&"+elements[i].id+"="+value;
			}
	    }
	}
	var xmlHttp=GetXmlHttpObject()
	document.getElementById("status").innerHTML = "Talletetaan...<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
	document.getElementById("animation").style.visibility = "visible";

	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="savePage.php";
	params=params+"&sid="+Math.random()+"&hpkajaxrequest=1";
	xmlHttp.onreadystatechange = 
	function()
	{
    	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
		{	
			if (xmlHttp.responseText == "SESSION EXPIRED")
				window.location.replace(location.hostname)
			//alert(xmlHttp.responseText);
			if (type =='savenewplayer')
				getPageContent('playermenu');
			else if (type == 'appointment')
				getPageContent('trainings');

			document.getElementById("status").innerHTML = "Valmis<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
			document.getElementById("animation").style.visibility = "hidden";
			if (evalFunction)
				eval(evalFunction);
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
	xmlHttp.send(params);
}


function doAction(action,params,infoText)
{
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="doAction.php";
	params=action+"=1&"+params+"&sid="+Math.random()+"&hpkajaxrequest=1";
	document.getElementById("status").innerHTML = infoText+"<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
	animpic = document.getElementById("animation");
	animpic.style.visibility = "visible";

	xmlHttp.onreadystatechange = 
	function()
	{   
    	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
		{//alert(xmlHttp.responseText);

			document.getElementById("status").innerHTML = "Valmis<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
			animpic.style.visibility = "hidden";
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}

function removePage(action,params,evalFunction)
{
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="doAction.php";
	params=action+"&"+params+"&sid="+Math.random()+"&hpkajaxrequest=1";
	document.getElementById("status").innerHTML = "Poistetaan...<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
	animpic = document.getElementById("animation");
	animpic.style.visibility = "visible";

	xmlHttp.onreadystatechange = 
	function()
	{   
    	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
		{//alert(xmlHttp.responseText);
			if (action == "removePersonalData=1" ||
				action == "removeMedcheckData=1" ||
				action == "removeSchoolData=1")
			{
				getPageContent("playercard");
			}
			else if (action == "removetrainingprogram=1")
			{
				getPageContent("personalprogram");
			}
			else if (action == "removeExternals=1")
			{
				printPage("removeexternalplayer");
			}
			else if (action == "removetransferredplayer=1" || action == "removetestmapping=1")
			{
				getPageContent("playertransfers");
			}
			else if (action == "removePlayersFromTransferlist=1")
			{
				printPage("transferout");
			}
			else if (action == "removeReceivedMessage=1" || action == "removeCheckedRecMessages=1")
			{
				getPageContent("receivedmessages");
			}
			else if (action == "removeSentMessage=1" || action == "removeCheckedSentMessages=1")
			{
				getPageContent("sentmessages");
			}
			else if (action == "removeEmail=1")
			{
				getPageContent("sendemail");
			}
			else if (action == "removePlayers=1")
			{
				printPage("removeplayer");
				getPageContent('playermenu');
			}
			else if (action == "removeMembers=1")
			{
				printPage("removemember");
			}
			else if (action == "removemessagelist=1")
			{
				printPage("removemessagelist");
			}
			else if (action == "removeemaillist=1")
			{
				printPage("removeemaillist");
			}
			else if (action == "removeDiaryPage=1")
			{
				getPageContent("diary");	
			}
			else if (action == "removeTestPage=1")
			{
				getPageContent("test");	
			}
			else if (action == "removeGroups=1")
			{
				printPage("removegroup");	
			}
			else if (action == "appointment=1")
			{
				getPageContent("trainings");	
			}
			else
			{
				document.getElementById("status").innerHTML = "Valmis<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
				animpic.style.visibility = "hidden";
			}
			if (evalFunction)
				eval(evalFunction);
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}


function printPage(page,contentAction)
{
	if (page == "replytomessage" || page == "replytoallmessage" || page == "forwardmessage")
		activemessid = document.getElementById("activemessageid").value;
	var xmlHttp=GetXmlHttpObject()
	
	document.getElementById("activepage").value = page;
	if (xmlHttp==null)
  	{
		alert ("Your browser does not support AJAX!");
		return;
  	}

	document.getElementById("status").innerHTML = "Odotetaan vastausta...<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
	animpic = document.getElementById("animation");
	animpic.style.visibility = "visible";
	var url="printPage.php";
	if (contentAction)
		params="page="+page+"&"+contentAction+"&sid="+Math.random()+"&hpkajaxrequest=1";
	else
		params="page="+page+"&sid="+Math.random()+"&hpkajaxrequest=1";
	xmlHttp.onreadystatechange=
	function () 
	{ 
		if (xmlHttp.readyState==4)
		{//alert(xmlHttp.responseText);
			if (xmlHttp.status == 200)
			{
				if (xmlHttp.responseText == "SESSION EXPIRED")
					window.location.replace("http://"+location.hostname+"/login.php")
				switch (page)
				{
					case "newtest":
					document.getElementById("testmgmt").innerHTML=xmlHttp.responseText+'<div class="close-popup"><img src="../img/close.gif" onclick="closeHelptext(document.getElementById(\'testmgmt\'))" /></div>';
					break;
					case "edittest":
					document.getElementById("testmgmt").innerHTML=xmlHttp.responseText+'<div class="close-popup"><img src="../img/close.gif" onclick="closeHelptext(document.getElementById(\'testmgmt\'))" /></div>';
					break;
					case "removetest":
					document.getElementById("testmgmt").innerHTML=xmlHttp.responseText+'<div class="close-popup"><img src="../img/close.gif" onclick="closeHelptext(document.getElementById(\'testmgmt\'))" /></div>';
					break;
					default:
					document.getElementById("content-wrapper").innerHTML=xmlHttp.responseText;
				}
				if (page == "trainingtool") {
					document.getElementById("content").style.left = "0px";
					document.getElementById("sidebar").style.display = "none";
				}
				else {
					document.getElementById("content").style.left = "253px";
					document.getElementById("sidebar").style.display = "block";
				}
				if (page == "replytomessage" || page == "replytoallmessage" || page == "forwardmessage")
					getPageContent(page,"messageid="+activemessid);
				else
					getPageContent(page,contentAction);
			}
			else {
				alert(xmlHttp.status);
				alert(xmlHttp.responseText);
				document.getElementById("status").innerHTML = "Sivua ei voida näyttää<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
			}
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}

function getPageContent(page,action)
{
	var fields;
	document.getElementById("status").innerHTML = "Odotetaan vastausta...<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
	animpic = document.getElementById("animation");
	animpic.style.visibility = "visible";
	if (action)
		fields = action+"&"+page+"=1";
	else
		fields = page+"=1";

	getContent(fields,page);

}

function sendClub()
{
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="setClub.php";
	params="club="+document.getElementById("club").value+"&sid="+Math.random()+"&hpkajaxrequest=1";
	xmlHttp.onreadystatechange = 
	function()
	{   
    	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
		{
        	if (xmlHttp.responseText)
			{//alert(xmlHttp.responseText);
            }
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}

function makeRecipientList(recipients,type)
{
	var id = 0;
	var sel = "";
	while (recipients.search("&id=") >= 0)
	{
		idStart = recipients.search("&id=")+4;
		idEnd = recipients.search("&fn=");
		id = recipients.substring(idStart,idEnd);
		firstnameStart = idEnd+4;
		firstnameEnd = recipients.search("&ln=");
		firstname = recipients.substring(firstnameStart,firstnameEnd);
		lastnameStart = firstnameEnd+4;
		lastnameEnd = recipients.search("<end>");
		lastname = recipients.substring(lastnameStart,lastnameEnd);
		if (id == "sep")
			sel = sel+firstname+""+lastname+"<br />";
		else if (id == "club")
			sel = sel+firstname+"<br />";
		else if (id == "-1")
			if (type == "listrecipientselection")
				sel = sel+"<span class=\"pointer-link\" onclick=\"getPageContent('listrecipientlist','recipient="+id+"')\"><b>"+firstname+" "+lastname+"</b></span><br />";
			else
				sel = sel+"<span class=\"pointer-link\" onclick=\"getPageContent('recipientlist','recipient="+id+"')\"><b>"+firstname+" "+lastname+"</b></span><br />";
		else if (id.search("team") >= 0)
			if (type == "listrecipientselection")
				sel = sel+"<span class=\"pointer-link\" onclick=\"getPageContent('listrecipientlist','recipientteam="+id.slice(4)+"')\"><b>"+firstname+" "+lastname+"</b></span><br />";
			else
				sel = sel+"<span class=\"pointer-link\" onclick=\"getPageContent('recipientlist','recipientteam="+id.slice(4)+"')\"><b>"+firstname+" "+lastname+"</b></span><br />";
		else
		{
			if (id.search("list") >= 0)
			{
				if (document.getElementById("rec"+id))
					sel = sel+"<input type=\"checkbox\" id=\""+id+"\" name=\""+firstname+"\" checked=\"checked\" onclick=\"selectRecipient(this,\'"+type+"\')\" />"+firstname+"<br />";
				else
					sel = sel+"<input type=\"checkbox\" id=\""+id+"\" name=\""+firstname+"\" onclick=\"selectRecipient(this,\'"+type+"\')\" />"+firstname+"<br />";				
			}
			else
			{
				if (document.getElementById("rec"+id))
					sel = sel+"<input type=\"checkbox\" id=\""+id+"\" name=\""+firstname+" "+lastname+"\" checked=\"checked\" onclick=\"selectRecipient(this,\'"+type+"\')\" />"+firstname+" "+lastname+"<br />";
				else
					sel = sel+"<input type=\"checkbox\" id=\""+id+"\" name=\""+firstname+" "+lastname+"\" onclick=\"selectRecipient(this,\'"+type+"\')\" />"+firstname+" "+lastname+"<br />";
			}
		}
		recipients = recipients.slice(lastnameEnd+5);
	}
	return(sel);
}

function addListRecipients(recipients)
{
	var id;
	var name;
	var removeImg;
	var newCell;
	var newRow;
	var i = 0;
	var element;
	while (recipients.search("&id=") >= 0)
	{
		idStart = recipients.search("&id=")+4;
		idEnd = recipients.search("&name=");
		id = recipients.substring(idStart,idEnd);
		nameStart = idEnd+6;
		nameEnd = recipients.search("<end>");
		name = recipients.substring(nameStart,nameEnd);
		element = document.getElementById(id);
		selectRecipient(element,"listrecipientselection");
		document.getElementById(id).checked = true;

		recipients = recipients.slice(nameEnd+5);
	}
}

function showListRecipients(recipients)
{
	var id;
	var name;
	var removeImg;
	var newCell;
	var newRow;
	var i = 0;
	var element;
	while (recipients.search("&id=") >= 0)
	{
		idStart = recipients.search("&id=")+4;
		idEnd = recipients.search("&name=");
		id = recipients.substring(idStart,idEnd);
		nameStart = idEnd+6;
		nameEnd = recipients.search("<end>");
		name = recipients.substring(nameStart,nameEnd);
		table = document.getElementById("listrecipienttable");
		rows = table.rows;
		rowCount = rows.length;
		newRow = table.insertRow(rowCount-1);
		newRow.id = "tr-"+id;
		newCell = newRow.insertCell(0);
		newCell.className = "transferredplayer";
		newCell.colSpan = "2";
		newCell.innerHTML = name;

		recipients = recipients.slice(nameEnd+5);
	}
}

function makeTeamList(teams)
{
var id;
	sel = "<ul>";
	while (teams.search("&id=") >= 0)
	{
		idStart = teams.search("&id=")+4;
		idEnd = teams.search("&tn=");
		id = teams.substring(idStart,idEnd);
		teamnameStart = idEnd+4;
		teamnameEnd = teams.search("<end>");
		teamname = teams.substring(teamnameStart,teamnameEnd);
		if (id == "club")
			sel = sel+"<li id=\"externalclubitem\">"+teamname+"</li>";
		else
			sel = sel+"<li id="+id+" class=\"dropdown-item\" onmouseout=\"normalizeLI(this)\" onmouseover=\"highLightLI(this)\" onclick=\"selectTeam(this,event)\" >"+teamname+"</li>";
		teams = teams.slice(teamnameEnd+5);
	}
	sel = sel+"</ul>";
	return(sel);
}

function makeTeamListMc(teams)
{
	var id = 0;
	var newOption;
	
	selection = document.getElementById("mcteamselection");
	newOption = document.createElement("option");
	newOption.innerHTML = "Valitse joukkue";
	selection.appendChild(newOption);
	while (teams.search("&id=") >= 0)
	{
		idStart = teams.search("&id=")+4;
		idEnd = teams.search("&name=");
		id = teams.substring(idStart,idEnd);
		nameStart = idEnd+6;
		nameEnd = teams.search("<end>");
		name = teams.substring(nameStart,nameEnd);
		newOption = document.createElement("option");
		newOption.setAttribute("value",id);
		newOption.innerHTML = name;
		selection.appendChild(newOption);	
		teams = teams.slice(nameEnd+5);
	}
	document.getElementById("sideaction").selectedIndex = 0;
	document.getElementById("mcteamselection").style.display = "block";
}

function makeOneTeamSelection(teams)
{
	var id;
	var sel = "";
	while (teams.search("&id=") >= 0)
	{
		idStart = teams.search("&id=")+4;
		idEnd = teams.search("&tn=");
		id = teams.substring(idStart,idEnd);
		teamnameStart = idEnd+4;
		teamnameEnd = teams.search("<end>");
		teamname = teams.substring(teamnameStart,teamnameEnd);
		sel = sel+"<input type=\"radio\" name=\"team\" id=\""+teamname+"\" value=\""+id+"\" onclick=\"showSelectedTeam(this)\" />"+teamname+"<br />";
		teams = teams.slice(teamnameEnd+5);
	}
	return(sel);
}

function makeTestSelection(tests,id)
{
	testarray = tests.split(";");
	testIds = testarray[0];
	testNames = testarray[1];
	testCount = testarray[2];
	if (id == "targettestselection")
	{
		var idBegin = "target";
		var target = true;
	}
	else
	{
		var idBegin = "";
		var target = false;
	}
	sel = "<ul>";
	origIdLength = testIds.length;
	origNameLength = testNames.length;
	while (testIds.length > 0)
	{
		testIdEnd = testIds.search("@");
		testNameEnd = testNames.search("@@@@");
		if (testIdEnd < 0)
		    testIdEnd = origIdLength+1;
		if (testNameEnd < 0)
		    testNameEnd = origNameLength+1;
		testId = testIds.substring(0,testIdEnd);
		testName = testNames.substring(0,testNameEnd);
		sel = sel+"<li id='"+idBegin+testId+"' class=\"dropdown-item\" onmouseout=\"normalizeLI(this)\" onmouseover=\"highLightLI(this)\" onclick=\"selectTest(this,"+testCount+","+target+")\" >"+testName+"</li>";
		testIds = testIds.slice(testIdEnd+1);
		testNames = testNames.slice(testNameEnd+4);
	}
	sel = sel+"</ul>";

	return(sel);
}

function setAttributes(external,page)
{
	if (external == 1)
		attr = true;
	else
		attr = false;
	switch (page)
	{
	case 'trainings' :
		document.getElementById("newprogram").disabled = attr;
		document.getElementById("savetrainingprogram").disabled = attr;
	break;
	case 'test' :
		document.getElementById("savetests").disabled = attr;
		document.getElementById("removetests").disabled = attr;
	break;
	}
}

function makeGroupSelection(groups)
{
	var newRow = document.getElementById("tr-appgroup");
	newRow.deleteCell(1);
	newCell = newRow.insertCell(1);
	newCell.innerHTML = groups;
}

function makeInfoMessages(messages)
{
	var id = 0, messageCount=0;
	var info;
	
	infosection = document.getElementById("infomessages");
	infosection.innerHTML = "";
	while (messages.search("<name>") >= 0)
	{
		nameStart = messages.search("<name>")+6;
		nameEnd = messages.search("</name>");
		name = messages.substring(nameStart,nameEnd);
		textStart = nameEnd+7;
		textEnd = messages.search("</text>");
		text = messages.substring(textStart,textEnd);
		info = document.createElement("div");
		info.innerHTML = text;
		switch (name)
		{
		case "newmessages":
			info.onclick = function() {setActivePage(document.getElementById('message'),'receivedmessages');};
			break;
		case "transferin":
			info.onclick = function() {setActivePage(document.getElementById('team'),'transferin');};
			break;
		case "transferout":
			info.onclick = function() {setActivePage(document.getElementById('team'),'transferout');};
			break;
		case "newregs":
			info.onclick = function() {setActivePage(document.getElementById('club'),'newregs');};
			break;
		case "openinvoices":
			info.onclick = function() {setActivePage(document.getElementById('owninfo'),'owninvoices');};
			break;
		case "overdueinvoices":
			info.onclick = function() {setActivePage(document.getElementById('owninfo'),'owninvoices');};
			break;
		}
		infosection.appendChild(info);
		messages= messages.slice(textEnd+7);
		messageCount++;
	}
	while (messageCount < 3)
	{
		info = document.createElement("div");
		infosection.appendChild(info);
		messageCount++;
	}
}

function addRecipientIds(recipientString)
{
	var ids = recipientString.split(";");
	var i = 0;
	var newRecipient;
	for (i = 0; i < ids.length; i++) {
		newRecipient = document.createElement("input");
		newRecipient.setAttribute("type","hidden");
		newRecipient.setAttribute("value",ids[i]);
		newRecipient.setAttribute("id","rec"+ids[i]);
		document.getElementById("sendmessageform").appendChild(newRecipient);
	}
}

function disableNotAllowedMessageTypes(type)
{
	if (type == 'message')
	{
		document.getElementById("messagetype_1").disabled = true;
		document.getElementById("messagetype_0").checked = true;
	}
	else
	{
		document.getElementById("messagetype_0").disabled = true;
		document.getElementById("messagetype_1").checked = true;
		document.getElementById("emailtitle").style.display = "block";
		document.getElementById("emailtitlelabel").style.display = "block";
	}
	document.getElementById("messagetype").value = type;
}

function addMessageLists(lists)
{
	var messagelistmenu = document.getElementById("messagelistselection");
	if (messagelistmenu.options.length > 1) // selection is already done once
		return;
	var id = 0;
	var newOption;
	while (lists.search("&id=") >= 0)
	{
		idStart = lists.search("&id=")+4;
		idEnd = lists.search("&fn=");
		id = lists.substring(idStart,idEnd);
		firstnameStart = idEnd+4;
		firstnameEnd = lists.search("&ln=");
		firstname = lists.substring(firstnameStart,firstnameEnd);
		lastnameStart = firstnameEnd+4;
		lastnameEnd = lists.search("<end>");
		if (firstname != "----")
		{
			newOption = document.createElement("option");
			newOption.value = id;
			newOption.innerHTML = firstname;
			messagelistmenu.appendChild(newOption);
		}
		lists = lists.slice(lastnameEnd+5);
	}	
}

function makeChart(domId,strXML){
	var CTStart = strXML.search("<graphname>")+11;
	var CTEnd = strXML.search("</graphname>");
	var heightStart = strXML.search("<graphheight>")+13;
	var heightEnd = strXML.search("</graphheight>");
	var chartHeight = strXML.substring(heightStart,heightEnd);
	var chartWidth;
	var chartType = strXML.substring(CTStart,CTEnd);
	var charts = strXML;
	var name,color,setindex=0, chartindex=0;
	var seltable, selrow, selrowcount=0, selcell, selcellcount=0, newrow=true, inputElement, divElement;
	var chartname;
	var chartXML;
	var header, headerindex = 0;
	var datasets;
	var table, createtable = false, row, cell, rowcount = 0;
	var selectorsCreated = false;
	document.getElementById("statisticscharts").innerHTML = "";
	if (charts.search("<graphtitle>") >= 0)
	{
		chartWidth = 500;
		var titles = new Array();
		j = 0;
		while (charts.search("<graphtitle>") >= 0)
		{
			CTStart = charts.search("<graphtitle>")+12;
			CTEnd = charts.search("</graphtitle>");
			titles[j++] = charts.substring(CTStart,CTEnd);
			charts = charts.slice(charts.search("</graphtitle>")+13);
		}
		table = document.createElement("table");
		document.getElementById("statisticscharts").appendChild(table);
		createtable = true;
	}
	else
		chartWidth = 600;
	initChartVars();
	charts.length = 0;
	document.getElementById("statisticsimg").innerHTML = "";
	seltable = document.createElement("table");
	document.getElementById("statisticsimg").appendChild(seltable);
	while (charts.search("<graph ") >= 0)
	{
		chartXML = charts.slice(charts.search("<graph "),charts.search("</graph>")+8)
		chartname = "chart"+chartindex+"Id";
		var chart = new FusionCharts("./FusionCharts/"+chartType,chartname, chartWidth, chartHeight);
		addChart(chartindex,chartname);
		addChartHeader(headerindex++,charts.slice(charts.search("<graph "),charts.search("<dataset")));
		datasets = charts.slice(charts.search("<dataset"),charts.search("</graph>"))
		while (datasets.search("<dataset") >= 0)
		{
			if (!selectorsCreated)
			{
				name = datasets.slice(datasets.search("seriesname='")+12,datasets.search("' color"));
				color = datasets.slice(datasets.search("color='")+7,datasets.search("' alpha"));
				if (newrow)
				{
					selrow = seltable.insertRow(selrowcount++);
					newrow = false;
				}
				selcell = selrow.insertCell(selcellcount++);
				selcell.innerHTML = name;
				selcell.style.background = "#"+color;
				selcell.style.padding = "2px";
				selcell.style.width = "120px";
				inputElement = document.createElement("input");
				inputElement.setAttribute("type","checkbox");
				inputElement.setAttribute("name","chartselector");
				inputElement.setAttribute("id","selector"+setindex);
				inputElement.onclick = updateAllCharts;
				selcell.appendChild(inputElement);
				inputElement.checked = true;
				inputElement.align = "right";
				if (selcellcount > 5)
				{
					selcellcount = 0;
					newrow = true;
				}
			}
			addChartDataset(setindex++,datasets.slice(datasets.search("<dataset"),datasets.search("</dataset>")+10));
			datasets = datasets.slice(datasets.search("</dataset>")+10);
		}
		selectorsCreated = true;

		divElement = document.createElement("div");
		chartHTMLid = "statisticschart"+chartindex;
		divElement.setAttribute("id",chartHTMLid);
		if (createtable)
		{
			row = table.insertRow(rowcount++);
			cell = row.insertCell(0);
			cell.className ="text-right";
			cell.innerHTML = titles[chartindex];
			cell = row.insertCell(1);
			cell.appendChild(divElement);
		}
		else
			document.getElementById("statisticscharts").appendChild(divElement);

		chartindex++;
		chart.setDataXML(chartXML);
		chart.render(chartHTMLid);
		charts = charts.slice(charts.search("</graph>")+8);
	}
	//Initialize graph with chart data returned by generateXML() function. [ note: the parameter 'this.document.productSelector.AnimateChart.checked' is passed to set animation property of the chart]
	//loading XML data into variable strXML 

	//Update it's XML - set animate Flag from AnimateChart checkbox in form
	//using updateChartXML method defined in FusionCharts.js
}

function getContent(str,page)
{
	var xmlHttp=GetXmlHttpObject()
	
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="getContent.php";
	document.getElementById("settings").innerHTML = "&nbsp;|&nbsp;<span class=\"non-active-link\" >Asetukset</span>";

	if (page == "sentmessages")
	{
		document.getElementById("emailtitlerow").style.display = "none";
		document.getElementById("emailtitle").style.display = "none";
	}

	params=str+"&sid="+Math.random()+"&hpkajaxrequest=1";//alert(params);
	xmlHttp.onreadystatechange = 
	function()
	{
    	if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
	        	if (xmlHttp.responseText)
				{
					if (xmlHttp.responseText == "SESSION EXPIRED")
						window.location.replace("http://"+location.hostname+"/login.php")
					response = xmlHttp.responseText;
					//alert(xmlHttp.responseText);
					if (page == 'statistics')
						document.getElementById("sideaction").selectedIndex = 0;
					while (response.search("<id>") >= 0)
					{
						idStart = response.search("<id>");
						idEnd = response.search("</id>");
						id = response.substring(idStart+4,idEnd);
						valueStart = response.search("<value>")
						valueEnd = response.search("</value>");
						value = response.substring(valueStart+7,valueEnd);//alert(id+"  "+value);
						if (id == "alert")
						{
							alert(value);
						}
						else if (id == "ext")
							setAttributes(value,page);
						else if (id == "allowedmessagetype")
							disableNotAllowedMessageTypes(value);
						else
						{
							if (id == "recipientselection" || id == "listrecipientselection" || id == "showmessagelistselection")
							{
								value = makeRecipientList(value,id);
							}
							else if (id == "messagelistid")
							{
								var messagelistoptions = document.getElementById("messagelistselection").options;
								messagelistoptions[0].selected = true;
							}
							else if (id == "teamselection")
							{
								value = makeTeamList(value);
							}
							else if (id == "oneteamselection")
							{
								value = makeOneTeamSelection(value);
							}
							else if (id == "stressdays")
								document.getElementById("stresstimedays").checked = true;
							else if (id == "stressstart")
								document.getElementById("stresstimecal").checked = true;
							else if (id == "testselection" || id == "targettestselection")
							{
								value = makeTestSelection(value,id);
							}
							else if (id == "listpub")
							{
								switch (value)
								{
								case "private":
									id = "listpub2";
									break;
								case "team":
									id = "listpub3";
									break;
								case "club":
									id = "listpub4";
									break;
								}
								value = true;
							}
							else if (id == "emailtitle")
							{
								if (navigator.appName == "Microsoft Internet Explorer")
								{
									document.getElementById("emailtitlerow").style.display = "inline";
									document.getElementById("emailtitle").style.display = "inline";
								}
								else
								{
									document.getElementById("emailtitlerow").style.display = "table-row";
									document.getElementById("emailtitle").style.display = "table-row";
								}
							}
	
							if (id == "listmembers")
							{
								addListRecipients(value);
							}
							else if (id == "showlistmembers")
							{
								showListRecipients(value);
							}
							else if (id == "stresslevel")
							{
								document.getElementById("stressinformation").style.display = "block";
								showStresslevel(value);
							}
							else if (id == "teamtestsummary")
							{
								document.getElementById("stressinformation").style.display = "none";
								showTeamtestsummary(value);
							}
							else if (id == "messagelistselection")
							{
								addMessageLists(value);
							}
							else if (id == "recipientids")
							{
								addRecipientIds(value)
							}
							else if (id == "stresssettings")
							{
								if (document.getElementById("stressinformation"))
									document.getElementById("stressinformation").style.display = "block";
								makeStresssettings(value)
							}
							else if (id == "playerdiarystats")
							{
								document.getElementById("stressinformation").style.display = "block";
								showPlayerDiaryStats(value)
							}
							else if (id == "sideselection")
							{
								makeTeamListMc(value)
							}
							else if (id == "personalinfo")
							{
								showPersonalInfo(value)
							}
							else if (id == "tr-appgroup")
							{
								makeGroupSelection(value);
							}
							else if (id == "newregs")
							{
								showNewRegistrants(value);
							}
							else if (id == "invoiceselection")
							{
								showInvoiceSelection(value);
							}
							else if (id == "invoicepayers")
							{
								showInvoicePayers(value);
							}
							else if (id == "invoicehistory")
							{
								showInvoiceHistory(value);
							}
							else if (id == "activeinvoices")
							{
								saveActiveInvoices(value);
							}
							else if (id == "invoice")
							{
								showInvoice(value);
							}
							else if (id == "invoicesettings")
							{
								showInvoiceSettings(value);
							}
							else if (id == "invoicetemplates")
							{
								showInvoiceTemplates(value);
							}
							else if (id == "invoicedefaults")
							{
								setInvoiceDefaults(value);
							}
							else if (id == "statisticsimg")
							{
								document.getElementById("stressinformation").style.display = "none";
								makeChart(id,value);	
							}
							else if (id == "telephone" || id == "email" || id == "relative")
							{
								showContacts(value,id);
							}				
							else if (id == "relativenames")
							{
								showRelatives(value);
							}
							else if (id == "infomessages")
							{
								makeInfoMessages(value);
							}
							else if (id == "uioptions")
							{
								document.getElementById("settings").innerHTML = "&nbsp;|&nbsp;<span class=\"active-link\" onClick=\"pageSettings('"+page+"','"+value+"')\" >Asetukset</span>";
							}
							else if (id == "groupoption")
							{
								if (value == "true")
								{
									if (document.forms['appointmentform'].apptype.length == 2)
									{
										document.forms['appointmentform'].apptype.options[1] = new Option('Ryhmän tapahtuma','group');
										document.forms['appointmentform'].apptype.options[2] = new Option('Joukkueen tapahtuma','team');
									}
								}
								else
								{
									if (document.forms['appointmentform'].apptype.length == 3)
									{
										document.forms['appointmentform'].apptype.options[1] = null;
									}
								}
							}
							else if (document.getElementById(id).type == 'radio')
								document.getElementById(id).checked = true;
							else if (document.getElementById(id).type == 'select-one')
							{
								selOptions = document.getElementById(id).options;
								for (i=0 ; i < document.getElementById(id).length ; i++)
								{
									if (selOptions[i].value == value)
									{
										document.getElementById(id).selectedIndex = i;
										break;
									}
								}
							}
							else if (document.getElementById(id).type == 'checkbox')
							{
								if (value == 1)
									document.getElementById(id).checked = true;
								else
									document.getElementById(id).checked = false;
							}
							else if (document.getElementById(id).value == undefined)
								document.getElementById(id).innerHTML = value;
							else
								document.getElementById(id).value = value;
						}
						response = response.slice(valueEnd+8);
					}
					document.getElementById("status").innerHTML = "Valmis<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
					document.getElementById("animation").style.visibility = "hidden";
	            }
			} // status == 200
			else
				document.getElementById("status").innerHTML = "Tietoja ei saatu<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
		} // readystate == 4
		else if (xmlHttp.readyState == 3)
		{
			document.getElementById("status").innerHTML = "Vastaanotetaan dataa...<img class=\"animation\" src=\"../img/ajax-loader.gif\" width=\"16\" height=\"16\" id=\"animation\" />";
			document.getElementById("animation").style.visibility = "visible";
		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function getClubSuggestions(clubInput)
{
	var xmlHttp=GetXmlHttpObject()
	
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="getClubHint.php";
	params="club="+document.getElementById("club").value+"&sid="+Math.random();
	xmlHttp.onreadystatechange = 
	function()
	{
    	if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
	        	if (xmlHttp.responseText)
				{
					//alert(xmlHttp.responseText);
					suggestion = document.getElementById("club-result-suggestions");
					suggestion.innerHTML = xmlHttp.responseText;
					var coords = findPos(clubInput);
					suggestion.style.position = "fixed";
					suggestion.style.left = coords[0]+"px";
					suggestion.style.top = clubInput.offsetHeight + coords[1]+"px";
					suggestion.style.width = clubInput.offsetWidth+"px";
					suggestion.style.display = 'block';
	            }
			} // status == 200
		} // readystate == 4
		else if (xmlHttp.readyState == 3)
		{

		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}

function getTeamSuggestions()
{
	var teamInput = document.getElementById("team");
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="getTeamHint.php";
	params="team=1&sid="+Math.random();
	xmlHttp.onreadystatechange = 
	function()
	{
    	if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
	        	if (xmlHttp.responseText)
				{
					//alert(xmlHttp.responseText);
					suggestion = document.getElementById("team-result-suggestions");
					suggestion.innerHTML = xmlHttp.responseText;
					var coords = findPos(teamInput);
					suggestion.style.position = "fixed";
					suggestion.style.left = coords[0]+"px";
					suggestion.style.top = teamInput.offsetHeight + coords[1]+"px";
					suggestion.style.width = teamInput.offsetWidth+"px";
					suggestion.style.display = 'block';
	            }
			} // status == 200
		} // readystate == 4
		else if (xmlHttp.readyState == 3)
		{

		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}

function getNews(type,newsid)
{
	var xmlHttp=GetXmlHttpObject()
	
	if (xmlHttp==null)
  	{
  		alert ("Your browser does not support AJAX!");
  		return;
  	}
	var url="getNews.php";

	params="news="+type+"&newsid="+newsid+"&sid="+Math.random();//alert(params);
	xmlHttp.onreadystatechange = 
	function()
	{
    	if (xmlHttp.readyState == 4)
		{
			if (xmlHttp.status == 200)
			{
	        	if (xmlHttp.responseText)
				{
					response = xmlHttp.responseText;//alert(xmlHttp.responseText);
					while (response.search("<id>") >= 0)
					{
						idStart = response.search("<id>");
						idEnd = response.search("</id>");
						id = response.substring(idStart+4,idEnd);
						valueStart = response.search("<value>")
						valueEnd = response.search("</value>");
						value = response.substring(valueStart+7,valueEnd);//alert(id+"  "+value);
						newsItem = document.getElementById(id);
						newsItem.innerHTML = value;
						if (id != "latestnews" && id != "latestnewstitle" && id != "newscontent")
							newsItem.style.visibility = "visible";
						response = response.slice(valueEnd+8);
					}
					document.getElementById("latestnews").style.display = "block";
					document.getElementById("latestnewstitle").style.display = "block";
					document.getElementById("newscontent").style.display = "block"
					document.getElementById("container").style.height = elementHeight(document.getElementById("newscontainer").offsetHeight+document.getElementById("header").offsetHeight+50)+"px";
					document.getElementById("sidebar").style.height = document.getElementById("container").offsetHeight-document.getElementById("content").offsetTop+"px";
					document.getElementById("newsbar").style.height = document.getElementById("sidebar").offsetHeight;

					for (i=1 ; i < 6 ; i++)
					{
						rmMenuItem = document.getElementById("menu"+i);
						rmMenuItem.parentNode.removeChild(rmMenuItem);
						document.getElementById("content"+i).style.display = "none";
						newMenuItem = document.createElement("div");
						newMenuItem.setAttribute("class","menuitem");
						newMenuItem.setAttribute("className","menuitem");
						newMenuItem.setAttribute("id","menu"+i);
						newMenuItem.onclick = changeContent;
						switch (i)
						{
						case 1 :
							newMenuItem.innerHTML = "ETUSIVU";
							break;
						case 2 :
							newMenuItem.innerHTML = "TUTUSTU";
							newMenuItem.onclick = showIntro;
							break;
						case 3 :
							newMenuItem.innerHTML = "HINNASTO";
							break;
						case 4 :
							newMenuItem.innerHTML = "TILAA";
							break;
						case 5 :
							newMenuItem.innerHTML = "ASIAKASPALVELU";
							break;
						}
						document.getElementById("sidebar").appendChild(newMenuItem);
						if(!NiftyCheck())
						    return;
						Rounded("div#menu"+i,"#D4EBF1","#e4f3f7");
					}
	            }
			} // status == 200
		} // readystate == 4
		else if (xmlHttp.readyState == 3)
		{

		}
	}
	xmlHttp.open("POST",url,true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.send(params);
}


function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
  	{
  	// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	}
	catch (e)
  	{
  	// Internet Explorer
  		try
    	{
    		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
  		catch (e)
    	{
    		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
  	}
	return xmlHttp;
}