var firstDayOfWeek = 1; // Monday

/********** tab pane functions **********/
function showTab(index, count)
{
	for(var i=0; i<count; i++)
	{
		var tabSelect = document.getElementById('tabselect'+i);
		var tab = document.getElementById('tab'+i);
		if(i==index)
		{
			if(tabSelect)tabSelect.className = "selectedmenuitem";
			if(tab)tab.style.display='block';
		}
		else 
		{
			if(tabSelect)tabSelect.className = "";
			if(tab)tab.style.display='none';
		}
	}
}
//function renderTabs()
//{
//	var tabs = document.getElementsByName("tabSelect");
//    for (var i=0; i < tabs.length; ++i) {
//      tabBorder.render(tabs[i]);
//    }
//}
/** ******** 28.1.2010: Common code for all wall messages now... ********* */
var xmlhttpwm,walltype,divnamewm,userid,receiverid,eventid,editing,refreshtime = 30000;
function addWallMessage(wt, wmdname, wminputname, parentid, uid, rid, eid)
{
	walltype=wt;divnamewm=wmdname;userid=uid;receiverid=rid;eventid=eid;
	sendWallMessage(wt, wmdname, wminputname, parentid, uid, rid, eid);
}
function sendWallMessage(wt, wmdname, wminputname, parentid, uid, rid, eid)
{
	var input = document.getElementById(wminputname); var msg = input.value; input.value= "";
	var request = "ajaxwm?action=add&walltype="+wt+"&msg="+encodeURIComponent(msg)+"&parentid="+parentid + "&rid="+rid + "&eid=" + eid;
	if(xmlhttpwm!=null){xmlhttpwm.abort();xmlhttpwm=null;}
	xmlhttpwm = createAjaxRequest(request, WMResponseHandler);
	editing=0;
}
function removeWallMessage(wt, id, sid, rid, eid)
{
	walltype = wt;
	var answer = confirm(strConfirmDelete);
	if (answer)
	{
		var request = "ajaxwm?action=removewm&walltype="+wt+"&id="+id+"&sid="+sid+"&rid="+rid+"&eid="+eid;
		if(xmlhttpwm!=null){xmlhttpwm.abort();xmlhttpwm=null;}
		xmlhttpwm = createAjaxRequest(request, WMResponseHandler);
	}
}
function getWallMessages(wt, wmdname, uid, rid, eid)
{
	walltype=wt;divnamewm=wmdname;userid=uid;receiverid=rid;eventid=eid;editing=0;
	refreshWM();
}
function refreshWM()
{
	if(editing==0)
	{
		var request = "ajaxwm?action=get&walltype="+walltype+"&rid=" + receiverid + "&eid=" + eventid;
		if(xmlhttpwm!=null){xmlhttpwm.abort();xmlhttpwm=null;}
		xmlhttpwm = createAjaxRequest(request, WMResponseHandler);
	}
	else setTimeout("refreshWM();", refreshtime);
}
function endPrevWMDiv(i, curid, curreceiverid, cureventid)
{
	var htmlStr="";
	//BEGIN comment writing. Add link to show comment edit div
	htmlStr += "<br><div style=\"width:100%;display:block;\">" + "<a style=\"margin-bottom:20px;\" href=\"javascript:showTable('comment" + i + "')\" onClick=\"disableRefreshWM();\">" + strComment + "</a>";

	// add comment edit and send div
	htmlStr += "<div id=\"comment" + i + "\" style=\"display: none;\">" +
			"<input class=\"input\" style=\"width:480px;height:20px;\" type=\"text\" id=\"wminput" + i + "\" name=\"wminput" + i + 
			"\" size=\"30\" maxlength=\"200\" onclick=\"textFieldOnClick(this)\" value=\"" + strWriteCommentHere + "\">";
	// send button
	htmlStr += "<input type=\"button\" class=\"jsbtn\" style=\"\" alt=\"\" onclick=\"sendWallMessage('"+ walltype + "','" + divnamewm + "', 'wminput" + i + 
			"', " + curid + ", " + userid + ", " + curreceiverid + ", " + cureventid + ");\" value=\"" + strSendComment + "\" title=\"" + strSendComment + "\">";
	// END comment writing
	htmlStr += "</div></div>";
	
	// END right column
	htmlStr += "</td>";			
	// END for root message div
	htmlStr += "</tr>";
	// END div for whole message
	htmlStr += "</table>";
	return htmlStr;
}
function WMResponseHandler()
{
	if(xmlhttpwm==null) return;
	if (xmlhttpwm.readyState==4)
	{
		var stat = xmlhttpwm.responseXML.getElementsByTagName("wallmessages")[0];
		if(stat==null) return;
		
		// last workouts
		var fl = stat.getElementsByTagName("wmlist");
		if(fl!=null)
		{
			var str = "";
			var htmlStr = "";
			var refresh = stat.getAttribute("refresh");

			var fb = xmlhttpwm.responseXML.getElementsByTagName("wmb");
			var curreceiverid = 0;
			var curid = 0;
			var cureventid = 0;
			for(var i=0; i<fb.length; i++)
			{
				var wallmessage = fb[i];
				var id = wallmessage.getAttribute("id");
				var sendername = wallmessage.getAttribute("s");
				var sid = wallmessage.getAttribute("sid");
				var rid = wallmessage.getAttribute("rid");
				var eid = wallmessage.getAttribute("eid");
				var etype = wallmessage.getAttribute("et");
				var eventname = wallmessage.getAttribute("e");
				var receivername = wallmessage.getAttribute("r");
				var message = wallmessage.getAttribute("m");
				var created = wallmessage.getAttribute("c");
				var depth = wallmessage.getAttribute("d");
				var msg = "";
				if(walltype!=2 && etype==3) msg = " " + strWroteToEventWall + " <a href=\"events?action=modify&id=" + eid + "\">" + eventname + "</a>: ";
				else if(walltype!=2 && rid!=sid) msg = " " + strWroteToUser + " <a href=\"frontpage?u=" + rid + "\">" + receivername + "</a>: ";
				if(depth==0)
				{
					//end previous div
					if(i>0) 
					{
						htmlStr += endPrevWMDiv(i, curid, curreceiverid, cureventid);
					}
					curid = id;
					curreceiverid = rid;
					cureventid = eid;

					// start new div
					htmlStr +=
					//BEGIN div for whole message
					"<table class=\"wmtable\">" +
					// BEGIN div for root message
					"<tr style=\"height:auto;\">" +
					
					// left column
					"<td style=\"width:100px;vertical-align:top;\">" +
					"<a href=\"frontpage?u=" + sid + "\"><img style=\"\" alt=\"\" src=\"image?action=getprofile&u=" + sid + "\" width=50 height=50 onClick=\"goToUrl('frontpage?u=" + sid + "')\"></a></td>" +
					
					// BEGIN right column
					"<td style=\"width:650px;vertical-align:top;margin-left:50px;\">" +
										
					// BEGIN message
					"<div style=\"width:100%;display:block;vertical-align:top;padding-bottom:10px;\">"; 

					message = message.replace(/&lt;/ig, '<');
					message = message.replace(/&gt;/ig, '>');
					message = message.replace(/&amp;/ig, '&');
					message = message.replace(/&quot;/ig, '\"');
					message = message.replace(/&apos;/ig, '\'');
					htmlStr += created + " <a href=\"frontpage?u=" + sid + "\">" + sendername + "</a> " + msg + message;
					if(sid==userid || rid==userid)
					{
						htmlStr += " <img class=\"icon\" alt=\"X\" src=\"" + imgTrash + "\" " + "onClick=\"removeWallMessage(" + walltype + "," + id + "," + sid + "," + rid + "," + eid + ");\" " + "title=\"" + strRemoveWM + "\" >";
					}

					//END message
					htmlStr += "</div>";					
				}
				else
				{
					//add response div
					htmlStr += "<div style=\"display:block;\">";
					
					htmlStr += "<div style=\"display:inline;margin-bottom:0px;\"><a href=\"frontpage?u=" + sid + "\"><img style=\"vertical-align:bottom\" alt=\"\" src=\"image?action=getprofile&u=" + sid + "\" width=32 height=32></a></div>";

					htmlStr += "<div style=\"display:inline;margin-left:10px;margin-bottom:0px\" id=msg\"" + "\">";
					htmlStr += "<div style=\"float:right;width:590px;margin-bottom:0px;\">";
					message = message.replace(/&lt;/ig, '<');
					message = message.replace(/&gt;/ig, '>');
					message = message.replace(/&amp;/ig, '&');
					message = message.replace(/&quot;/ig, '\"');
					message = message.replace(/&apos;/ig, '\'');
					htmlStr += created + " <a href=\"frontpage?u=" + sid + "\">" + sendername + "</a> " + message;
					if(sid==userid || rid==userid)
					{
						htmlStr += " <img class=\"icon\" alt=\"X\" src=\"" + imgTrash + "\" " + "onClick=\"removeWallMessage(" + walltype + "," + id + "," + sid + "," + rid + "," + eid + ");\" " + "title=\"" + strRemoveWM + "\" >";
					}
					htmlStr += "</div></div></div><br>";
				}
			}
			
			if(fb.length>0)
			{
				htmlStr += endPrevWMDiv(i, curid, curreceiverid, cureventid);
			}

			if(htmlStr!=null)
			{
				htmlStr += "</div>";
				var div = document.getElementById(divnamewm);
				if(htmlStr.length>0) div.innerHTML=htmlStr;					
				else div.innerHTML="";
			}
			if(refresh==1)
			{
				//refresh after 60s
				var t=setTimeout("refreshWM();", refreshtime);
			}
		}
	}
	
}
function disableRefreshWM()
{
	editing = 1;
}


var xmlhttpmaar;
function markAllPmAsRead()
{
	var request = "messages?action=markallasread";
	if(xmlhttpmaar!=null){xmlhttpmaar.abort();xmlhttpmaar=null;}
	xmlhttpmaar = createAjaxRequest(request, maarResponseHandler);
}
function maarResponseHandler()
{
	if(xmlhttpmaar==null) return;
	if (xmlhttpmaar.readyState==4)
	{
		//alert('OK');
	}
}
/********** REPORTS **********/
var xmlhttpreport;
function showReport(uid)
{
	var rt=document.getElementById("reporttype").value;
	var sd=document.getElementById("startdate").value;
	var ed=document.getElementById("enddate").value;
	var pi=document.getElementById("pi").value;
	var sw=document.getElementById("sw").value;
	var qs=document.getElementById("qs").value;
	var slist=document.getElementById("slist").value;
	var qlist=document.getElementById("qlist").value;

  	var selObj = document.getElementById('reporttype');
  	var i,reportTypeStr="";
  	for (i=0; i<selObj.options.length; i++){if (selObj.options[i].selected){reportTypeStr+=(selObj.options[i].value + ";");}}
	
  	selObj = document.getElementById('slist');
  	var sportStr="";
  	//if(!selObj.disabled) 
  		for (i=0; i<selObj.options.length; i++){if (selObj.options[i].selected){sportStr+=(selObj.options[i].value + ";");}}
  	if(sportStr.indexOf("0;") == 0) sportStr = "0;";
  	else if(sportStr=='') sportStr = "0;";
  		
  	var selObj = document.getElementById('qlist');
  	var qualityStr="";
  	//if(!selObj.disabled)
  		for (i=0; i<selObj.options.length; i++){if (selObj.options[i].selected){qualityStr+=(selObj.options[i].value + ";");}}
  	if(qualityStr.indexOf("0;") == 0) qualityStr = "0;";
  	else if(qualityStr=='') qualityStr = "0;";

  	//alert('sportStr='+sportStr+",qualityStr="+qualityStr);
  	var request = "reports?u=" + uid + "&ajax=1" + ("&action=reports&reporttype=" + reportTypeStr + "&startdate=" + sd + "&enddate=" + ed + "&pi=" + pi + "&sw=" + sw + "&qs=" + qs + "&slist=" + sportStr + "&qlist=" + qualityStr);
	//alert('LENGTH='+request.length);
  	if(xmlhttpreport!=null){xmlhttpreport.abort();xmlhttpreport=null;}
	xmlhttpreport = createAjaxRequest( request, reportHandler);
}
function reportHandler()
{
	if(xmlhttpreport==null) return;
	if (xmlhttpreport.readyState==4)
	{
		//alert(xmlhttpreport.responseText);
		document.getElementById("pi").disabled=true;
		document.getElementById("sw").disabled=true;
		document.getElementById("qs").disabled=true;
		document.getElementById("slist").disabled=true;
		document.getElementById("qlist").disabled=true;
		
		var div = document.getElementById("reportcanvas");
		div.innerHTML = xmlhttpreport.responseText;
		//document.getElementById("pi").disabled=false;
		var x = div.getElementsByTagName("script");   
		for(var i=0;i<x.length;i++)  
		{  
			eval(x[i].text);
		}  
		
	}	
}
/********** REPORTS **********/

/********** EVENTS **********/
//function createEventFromWorkout(wid, userid, type, sday, stime, n, desc, loc)
//{
//	var startday=document.getElementById(sday).value;var starttime=document.getElementById(stime).value;
//	var name=document.getElementById(n).value;var description=document.getElementById(desc).value;
//	var location=document.getElementById(loc).value;
//	goToUrl( "events?action=add&wid="+wid+"&u=" + userid + "&startday=" + startday + "&starttime=" + starttime + "&name=" + name + "&description=" + description + "&location=" + location);
//}

/********** WORKOUT **********/
function calculateSpeeds(index)
{
	//alert("calculateSpeed()");
	for(var i=0; i<index; i++) calculateSubSpeed(i);
}
function calculateSubSpeed(i)
{
	try
	{
		var dh = document.getElementById("subduration_h"+i+"");
		var dm = document.getElementById("subduration_m"+i+"");
		var ds = document.getElementById("subduration_s"+i+"");
		var dl = document.getElementById("sublength"+i+"");
		//alert(document.getElementById("subduration_h" + i + ""));
		var dur = 3600000*dh.value + 60000*dm.value +1000*ds.value;
		
		//speed km/h
		var kmhf = document.getElementById("sub_speed"+i+"");
		var kmh=0;if(dur>0)kmh = ((dl.value * 3600000) / dur);
		kmhf.innerHTML = kmh.toFixed(2) + " km/h";
		
		//pace min/km
		var pacef = document.getElementById("sub_pace"+i+"");
		var pm=0,ps=0;
		if(dl.value>0)
		{
			var pace = dur / (dl.value);
			pm= Math.floor(pace/60000);
			ps= Math.round( (pace%60000) / 1000);
		}
		if(ps<10) ps="0"+ps;
		pacef.innerHTML = pm + ":" + ps + "/km";

	}catch(e) {}
}
//function createWorkoutFromEvent(eid, userid, type, sday, stime, n, desc, loc)
//{
//	var startday=document.getElementById(sday).value;var starttime=document.getElementById(stime).value;
//	var name=document.getElementById(n).value;var description=document.getElementById(desc).value;
//	var location=document.getElementById(loc).value;
//	goToUrl( "workout?action=add&eid="+eid+"&u=" + userid + "&type=0&startday=" + startday + "&starttime=" + starttime + "&name=" + name + "&description=" + description + "&location=" + location);
//}

var currentWorkoutId=0,newestHrGpsId,currentHrGpsId=0,userId=0,hrxmlhttp,hrmValues = null;
var hrDivName, hrIdName, hrGraphDiv, mapContainer, mapDivName, mapIdName, mapCanvasName;
function initHrGps(hrdn, hrid, hrg, mapcnt, mapdn, mapid, mapc, wid, userid)
{
	hrDivName=hrdn;hrIdName=hrid;hrGraphDiv=hrg;
	mapContainer=mapcnt;mapDivName=mapdn;mapIdName=mapid;mapCanvasName=mapc;

	currentWorkoutId = wid;userId = userid;
}
function createHrGpsAttachDialog(type, parent)
{				
 	var bodyHeight = Math.max(document.body.offsetHeight, window.innerHeight);
 	var bodyWidth = document.body.offsetWidth;
 	var x = parent.offsetLeft;// + parent.width;
 	var y = parent.offsetTop + parent.offsetHeight;// + parent.height;

 	// deal with elements inside tables and such
 	var p = parent;
 	while (p.offsetParent) 
 	{
 		p = p.offsetParent;
 	    if(p.offsetLeft>0) x += p.offsetLeft;
 	    if(p.offsetTop>0) y += p.offsetTop;
 	}
 	if( (x+300)>document.body.offsetWidth){x-=300;}
 	if(y<0) y=50;
 	//y-=300;
 	x=200;
	
	var dialogid = "hrgpsdlg";
	var hrdlgdiv = document.getElementById(dialogid);
	if (!hrdlgdiv) 
	{
		var hrdlgdiv = document.createElement("div");
		hrdlgdiv.setAttribute("id", dialogid);
		hrdlgdiv.setAttribute("style", "padding:0;margin:0;visibility:hidden;background-color:#ffff;");
	}

	var attachStr = strAttachHRToWorkout;if(type==1) attachStr = strAttachRouteToWorkout;		
	var importStr=strImportHRDFromFile;if(type==1)importStr=strImportRouteFromFile;
	var selectStr=strSelectHRDFromDB;if(type==1)selectStr=strSelectRouteFromDB;

	var strDrawRouteBtn = "";
	if(type==1) strDrawRouteBtn = "<input type=\"button\" class=\"jsbtn\" style=\"float:right;margin-bottom:20px;\" value=\"" + strCreateNewRoute + "\" onclick=\"editRoute()\">";

	hrdlgdiv.innerHTML = 
	"<div style=\"background-color:#ffffff;border: 1px solid #000;height:400px\">" +
	
	"<div id=\"hrdtitle\" style=\"height:25px;padding:5px;margin:0;margin-bottom:20px;border: 1px solid #000;background: #B4C9C9;\">" + 
	"<span style=\"float:left;\">" + attachStr + "</span>" +
	"<span style=\"float:right;\"><a class=\"image\" title=\"" + strClose + "\" href=\"javascript:closeHrAttachDialog();\"><img class=\"icon\" alt=\"X\" src=\"" + imgClose +"\"></a></span></div>" +
	
	"<div id=\"hrdlist\" style=\"padding:0;margin:5px;\">" +
	
	"<form id=\"uploadfile\" method=\"post\" ENCTYPE=\"multipart/form-data\" accept-charset=\"UTF-8\" action=\"ajaxhrdata?action=upload\">" +
	"<div style=\"font-weight:bold;\">" + importStr + "</div>" +
	"<input type=\"hidden\" id=\"wid\" name=\"wid\" value=\"" + currentWorkoutId + "\">" +
	"<input type=\"file\" id=\"uploadFileName\" name=\"filename\" style=\"width:auto;\" size=\"40\" onChange=\"uploadHrFile();return false;\" ><br>" +
	"<iframe id=\"upload_target\" name=\"upload_target\" src=\"\" style=\"width:0;height:0;border:0px solid #fff;\"></iframe>" +
	"</form>" +

	"<div style=\"margin-top:20px;font-weight:bold;\">" + selectStr + "</div>" +
	"<div id=\"hrgpslistdiv\" style=\"display:block;\"></div>" +
	
	"<div style=\"height:40px;\"><input type=\"checkbox\" style=\"width:20px\" id=\"importfromhrfile\" name=\"importfromhrfile\" value=\"importfromhrfile\" CHECKED> " + strCreateWorkout + "</div>" +
	"<div><input type=\"button\" class=\"jsbtn\" style=\"float:left;margin-bottom:20px;\" value=\"" + strAttach + "\" onclick=\"getSelectedHrGraph();return false;\"> " +
	strDrawRouteBtn +
	"</div>" +
	"</div></div>";

	hrdlgdiv.style.position = "absolute";
	hrdlgdiv.style.left = x + "px";
	hrdlgdiv.style.top = y + "px";
	hrdlgdiv.style.visibility = (hrdlgdiv.style.visibility == "visible" ? "hidden" : "visible");
	hrdlgdiv.style.display = "block";
	hrdlgdiv.style.zIndex = 10000;
	hrdlgdiv.style.width = "450px";
	hrdlgdiv.style.height = "300px";

	document.body.appendChild(hrdlgdiv);
	
	// get hrm files from db using ajax
	getHrGraphs(type);
}
//get hrm files from db using ajax
function getHrGraphs(type)
{
	//alert(getHrGraphs);
	var sd = document.getElementById("startday");var sdate = sd.value;
	if(hrxmlhttp!=null){hrxmlhttp.abort();hrxmlhttp=null;}
	var request = "ajaxhrdata?action=get&t=" + encodeURIComponent(type) + "&u=" + encodeURIComponent(userId) + "&startdate=" + encodeURIComponent(sdate);
	hrxmlhttp = createAjaxRequest(request, hrDialogResponseHandler);
}

//handle ajax response when hr graph list has been requested
function hrDialogResponseHandler()
{
	if(hrxmlhttp==null) return;
	var index=0;
	if (hrxmlhttp.readyState==4 && hrxmlhttp.status==200)
	{
		//alert("hrxmlhttp.readyState==4, hrxmlhttp.status=200");
		var hrdlist = hrxmlhttp.responseXML.getElementsByTagName("hrdatalist")[0];
		var hrditem = hrxmlhttp.responseXML.getElementsByTagName("hrdataitem")[0];

		newestHrGpsId=0;
		if(hrdlist!=null)
		{
			var str="",htmlStr="",selectedIndex=0;
			var fb = hrdlist.getElementsByTagName("hrdatabean");
			hrmValues = new Array(fb.length);
			for(var i=0; i<fb.length; i++){hrmValues[i] = new Array(9);}
	
			htmlStr += "<SELECT size=10 class=\"sports\" id=\"hrgpsidlist\" name=\"hrgpsidlist\" style=\"width:100%;\" onChange=\"\">";
			for(var i=0; i<fb.length; i++)
			{
				var hrdata=fb[i],id=hrdata.getAttribute("id"),name=hrdata.getAttribute("name");
				hrmValues[i][0] = hrdata.getAttribute("startdate");
				hrmValues[i][1] = hrdata.getAttribute("starttime");
				hrmValues[i][2] = hrdata.getAttribute("calories");
				hrmValues[i][3] = hrdata.getAttribute("maxhr");
				hrmValues[i][4] = hrdata.getAttribute("avghr");
				hrmValues[i][5] = hrdata.getAttribute("epoc");
				hrmValues[i][6] = hrdata.getAttribute("te");
				hrmValues[i][7] = hrdata.getAttribute("duration");
				hrmValues[i][8] = hrdata.getAttribute("length");
	
				if(id>newestHrGpsId) newestHrGpsId=id;
				var selected = "";
				if(id==currentHrGpsId)
				{
					selected = " SELECTED ";
					selectedIndex = i;
				}
				//htmlStr += "<OPTION value=\"" + id + "\" " + selected + ">" + startdate + " " + starttime + " " + duration + " " + minhr + "-" + maxhr + " : " + name + "</OPTION>";
				htmlStr += "<OPTION value=\"" + id + "\" " + selected + ">" + hrmValues[i][0] + " " + hrmValues[i][1] +  "-----" + name + "</OPTION>";
			}
			htmlStr += "</SELECT>";
			document.getElementById("hrgpslistdiv").innerHTML = htmlStr;
		}
		if(hrditem!=null)
		{
			//document.getElementById(mapCanvasName).style.display="none";
			//document.getElementById(hrGraphDiv).style.display="none";

			var str="", htmlStr="", fb=hrditem.getElementsByTagName("hrdatabean"); hrddata=new Array(9);
			if(fb.length>0)
			{
				var hrdata=fb[0], id=hrdata.getAttribute("id"), type=hrdata.getAttribute("type"), name=hrdata.getAttribute("name");
				hrddata[0] = hrdata.getAttribute("startdate");
				hrddata[1] = hrdata.getAttribute("starttime");
				hrddata[2] = hrdata.getAttribute("calories");
				hrddata[3] = hrdata.getAttribute("maxhr");
				hrddata[4] = hrdata.getAttribute("avghr");
				hrddata[5] = hrdata.getAttribute("epoc");
				hrddata[6] = hrdata.getAttribute("te");
				hrddata[7] = hrdata.getAttribute("duration");
				hrddata[8] = hrdata.getAttribute("length");
				if(id>newestHrGpsId)
				{
					if(hrultimer) clearTimeout(hrultimer);
					closeHrAttachDialog();
					if(type==0) 
					{
						attachHrGraph(id, hrddata);
						document.getElementById(hrGraphDiv).style.display="block";
					}
					else if(type==1)
					{
						document.getElementById(mapIdName).value = id;
						importGpsData(hrddata);
						document.getElementById(mapCanvasName).style.display="block";
					}
				}
			}
			
			var routelist=hrxmlhttp.responseXML.getElementsByTagName("woroute")[0];
			if(routelist!=null)
			{
				routePoints = [];
				lapPoints = [];
				//coordinates as long text node
				var rpList = routelist.getElementsByTagName("latlon");
				if(rpList!=null) if(rpList.length>0)
				{
					routePoints = new Array(rpList.length);
					routePointTimes = new Array(rpList.length);
					playing=false;
					for(var i=0; i<rpList.length; i++)
					{
						var p=rpList[i], hr=p.getAttribute("hr"),lat=p.getAttribute("lat"), lon=p.getAttribute("lon"), time=p.getAttribute("time"),dist=p.getAttribute("dist");
						routePoints[i] = new RoutePoint(lat,lon,time,hr,dist);
					}
					
					//get possible lap points
					var lapList = routelist.getElementsByTagName("lap");
					if(lapList!=null) if(lapList.length>0)
					{
						lapPoints = new Array(lapList.length);
						for(var i=0; i<lapList.length; i++)
						{
							var p=lapList[i],hr=p.getAttribute("hr"),lat=p.getAttribute("lat"), lon=p.getAttribute("lon"), time=p.getAttribute("time"),dist=p.getAttribute("dist");
							lapPoints[i] = new RoutePoint(lat,lon,time,hr,dist);
						}
					}
					
					pminhr = hrdata.getAttribute("min");pmaxhr = hrdata.getAttribute("max");
					anaK = hrdata.getAttribute("anak");aerK = hrdata.getAttribute("aerk");
					if(pminhr==0) pminhr=50;if(pmaxhr==0) pmaxhr=200;
					if(anaK==0) anaK=165;if(aerK==0) aerK=145;
					showWorkoutRoute();
				}				
			}
			
		}
		hrdlist=null;
		hrditem=null;
		
		return false;
	}
}
function closeHrAttachDialog()
{				
	var dialog = document.getElementById("hrgpsdlg");
	if(dialog!=null)
	{
		dialog.style.visibility = "hidden";
	}
}

function getSelectedHrGraph()
{
	newestHrGpsId = 0;
	var list = document.getElementById("hrgpsidlist");
	if(list!=null)
	{
		var selIndex = list.selectedIndex;
		if(selIndex>-1)	getHrGpsGraph(list.options[selIndex].value);
	}
}
function showHrGpsGraph(hrgpsid)
{
	showMap(1, 'mapdiv', 'mapcanvas', 'location', '1', true);
	if(hrxmlhttp!=null)setTimeout("getHrGpsGraph("+hrgpsid+");",1000);
	else getHrGpsGraph(hrgpsid);
}
function getHrGpsGraph(hrgpsid)
{
	if(hrxmlhttp!=null){hrxmlhttp.abort();hrxmlhttp=null;}
	var request = "ajaxhrdata?action=gethrd&u=" + encodeURIComponent(userId) + "&hrgpsid=" + encodeURIComponent(hrgpsid);
	hrxmlhttp = createAjaxRequest(request, hrDialogResponseHandler);
}
var attachtime;
//detach hr graph from workout
function detachHrGpsGraph(type)
{
	if(type==0)
	{
		document.getElementById(hrGraphDiv).style.display="none";
		document.getElementById(hrIdName).value = 0;
	}
	else
	{
		document.getElementById(mapCanvasName).style.display="none";
		document.getElementById("routeeditdiv").style.display="none";
		//document.getElementById("editroutehelp").style.display="none";
		document.getElementById(mapIdName).value = 0;
	}
	currentHrGpsId = 0;
}
var hrdWidth=750;
var hrdHeight=400;
var hrddata;
//attach hr graph to workout
function attachHrGraph(hrgpsid, hrddata)
{
	var dlg = document.getElementById("hrgpsdlg");if(dlg!=null)dlg.style.cursor = "default";
	var lst=document.getElementById("hrgpsidlist");if(lst!=null)lst.style.cursor = "default";
	currentHrdGpsId = hrgpsid;
	var d = new Date();
	var ms = d.getTime();

	//hack for fucking IE
	if( (ms-attachtime)<1000)
	{
		//alert("NOT YET AGAIN!: attachtime="+attachtime+", ms="+ms);
		return;
	}
	attachtime = ms;
	
	var graph = document.getElementById(hrGraphDiv);
	graph.style.visibility = "visible";
	graph.innerHTML = 
		"<a href=\"\" onclick=\"var nw=openNewWindow('HrGraphWindow.jsp?u=" + userId + "&amp;hrdid=" + hrgpsid + 
		"','HRG_"+userId+"','height=600,width=1024,toolbar=no,scrollbars=yes,resizable=yes');nw.focus();return false;\">" +
	
		"<img alt=\"X\" onmousemove=\"showCurrentPoint(event, this)\" src=\"hrgraph?u=" +	userId + "&amp;hrdid=" + hrgpsid + 
		"&amp;width=" + hrdWidth + "&amp;height=" + hrdHeight + "\" title=\"" + strClickToShowBiggerImage + "\">" + "</a>" +

		//hr distribution graph
		"<a href=\"\" onclick=\"var nw=openNewWindow('HrGraphWindow.jsp?u=" + userId + "&amp;vm=2&amp;hrdid=" + hrgpsid + 
		"','HRG_"+userId+"','height=600,width=1024,toolbar=no,scrollbars=yes,resizable=yes');nw.focus();return false;\">" +
	
		"<img alt=\"X\" onmousemove=\"showCurrentPoint(event, this)\" src=\"hrgraph?u=" +	userId + "&amp;hrdid=" + hrgpsid + 
		"&amp;vm=2&amp;width=" + hrdWidth + "&amp;height=" + hrdHeight + "\" title=\"" + strClickToShowBiggerImage + "\">" + "</a>";

	document.getElementById("hrdid").value = hrgpsid;
	importData(hrddata);
}
function importData(data)
{
	var importFromHrFile = document.getElementById("importfromhrfile");
	if(importFromHrFile==null) return;
	if(importfromhrfile.checked && data!=null)
	{
		//import values from hrm file to workout
		document.getElementById("subquality0").selectedIndex = 2;//2=peruskestävyys
	
		//document.getElementById("startdate").value = data[0]; 
		document.getElementById("starttime").value = data[1]; 
		document.getElementById("calories").value = data[2]; 
		document.getElementById("maxhr").value = data[3]; 
		document.getElementById("averagehr").value = data[4]; 
		document.getElementById("epoc").value = data[5]; 
		document.getElementById("te").value = data[6]; 
		
		var sec = data[7] / 1000;//milliseconds->seconds
		var hours = Math.floor(sec / 3600);	var minutes = Math.floor((sec % 3600) / 60); var seconds = ((sec % 3600) % 60);
		var lzm = ""; var lzs="";if(minutes<10) lzm="0";if(seconds<10) lzs="0";
		document.getElementById("subduration_h0").value = hours.toFixed(0);
		document.getElementById("subduration_m0").value = lzm + minutes.toFixed(00);
		document.getElementById("subduration_s0").value = lzs + seconds.toFixed(00);
		
		document.getElementById("sublength0").value = (data[8] / 1000).toFixed(2); 
		calculateSubSpeed(0);
	}
}
function importGpsData(data)
{
	var importFromHrFile = document.getElementById("importfromhrfile");
	if(importFromHrFile==null) return;
	if(importfromhrfile.checked && data!=null)
	{
		//import values from gpx/kml file to workout
		document.getElementById("subquality0").selectedIndex = 1;
		document.getElementById("sublength0").value = (data[8] / 1000).toFixed(2); 
		calculateSubSpeed(0);
	}
}
function reloadHrGraph()
{
	var hrgpsid = document.getElementById(hrIdName).value;
	var graph = document.getElementById(hrGraphDiv);
	graph.innerHTML = 
		"<a href=\"\" onclick=\"var nw=openNewWindow('HrGraphWindow.jsp?u=" + userId + "&amp;hrdid=" + hrgpsid + 
		"','HRG_"+userId+"','height=600,width=1024,toolbar=no,scrollbars=yes,resizable=yes');nw.focus();return false;\">" +
	
		"<img alt=\"X\" src=\"hrgraph?u=" +	userId + "&amp;hrdid=" + hrgpsid + 
		"&amp;width=" + hrdWidth + "&amp;height=" + hrdHeight + "\" title=\"" + strClickToShowBiggerImage + "\">" + "</a>";
}


/** ******** Google maps functionality ********* */
function zoomMap(type, zoomin)
{
//	alert('zoommap');
	var md = document.getElementById(mapContainer);
	var mc = document.getElementById(mapCanvasName);

	var hrd = document.getElementById(hrDivName);
	var hrg = document.getElementById(hrGraphDiv);
	var curw = md.style.width;
	if(type==0) curw = hrd.style.width;

	var mddisp=md.style.display;var hddisp=hrd.style.display;

	hrd.className="onecolumnnoborder";hrd.style.width='750px';hrg.style.height='400px';hrdWidth=750;hrdHeight=400;reloadHrGraph();
	//hrd.style.height='400px';
	if(map!=null)
	{
		md.className="onecolumnnoborder";md.style.width='750px';mc.style.width='750px';mc.style.height='400px';
		var red=document.getElementById("routeeditdiv");
		if(red!=null)red.style.display="block";
		//var erdh=document.getElementById("editroutehelp");
		//if(erdh!=null)erdh.style.display="block";

		map.enableScrollWheelZoom();
		//map.enableContinuousZoom();

		map.checkResize();
		map.setCenter(mapCenter);
		mc.style.display=mddisp;
	}
	hrd.style.display=hddisp;

	//if(type==0) goToUrl("#"+hrDivName);
	//else goToUrl("#editroutehelp");
	
}
var map = null, geocoder = null, address=null, marker, armodify=0, mapCenter,mapLCListener,mapRCListener;
function showMap(redit, mapdivname, mapcanvasname, locationfieldname, armod, scroll, prefergm)
{
//	alert("showMap: G_API_VERSION="+G_API_VERSION);
	//google.load("maps", "2.232");
	
	if (GBrowserIsCompatible())
	{
		armodify = armod;
		// map initialization
		document.getElementById(mapdivname).style.display="block";
		document.getElementById(mapcanvasname).style.display="block";

		if(map==null)
		{
		    var copyOSM = new GCopyrightCollection("<a target=\"_blank\" href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
		    copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));
			var tilesMapnik = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
			var mapMapnik = new GMapType([tilesMapnik],G_NORMAL_MAP.getProjection(), "OSM");
			if(prefergm) map = new GMap2(document.getElementById(mapCanvasName), { mapTypes: [G_NORMAL_MAP, mapMapnik, G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP] });
			else map = new GMap2(document.getElementById(mapCanvasName), { mapTypes: [mapMapnik, G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP] });

			map.addControl(new GSmallZoomControl3D(100)); 
			//map.addControl(new GLargeMapControl3D(100));
			map.addControl(new GMapTypeControl());

			createIcons();
		}
		map.clearOverlays();

		map.enableScrollWheelZoom();
//		if(scroll)
//		{
//			map.enableScrollWheelZoom();
//			//map.enableContinuousZoom();
//		}
//		else
//		{
//			map.disableScrollWheelZoom();
//			//map.disableContinuousZoom();
//		}


		// try first to get coordinates
		var lat = document.getElementById("latitude").value;
		var lon = document.getElementById("longitude").value;
		var addr = document.getElementById(locationfieldname).value;

		var useGeoCoder = false;
		// use always geocoder if we dont have coordinates
		if(lat==0 || lon==0) useGeoCoder = true;

		//we are adding new place
		else if(addr!=null && addr!="" && address!=null) 
		{
			if(addr!=address) useGeoCoder = true;
		}
		address=addr;

		if(useGeoCoder && geocoder==null) geocoder = new GClientGeocoder();
		if (useGeoCoder && geocoder && (address==null || address=="") )
		{
			mapCenter = new GLatLng(65.0097,25.4728);
			map.setCenter(mapCenter);
			showMarker(mapCenter, 3);
		}
		else if (useGeoCoder && geocoder)
		{
			//alert("useGeoCoder && geocoder");
			geocoder.getLatLng( address, 
				function(point)
				{
					if (!point)
					{
						//alert(mapsAddressNotFound1 + address + mapsAddressNotFound2);
						mapCenter = new GLatLng(65.0097,25.4728);
						map.setCenter(mapCenter);
						showMarker(mapCenter, 3);
					}
					else
					{
						mapCenter = point;
						map.setCenter(point);
						showMarker(point, 10);
					}
				});
		}
		else
		{
			mapCenter = new GLatLng(lat,lon);
			map.setCenter(mapCenter);
			showMarker(mapCenter, 11);
		}

		map.getDragObject().setDraggableCursor("default");
		if(redit==1)
		{
			if(mapLCListener!=null)GEvent.removeListener(mapLCListener);
			if(mapRCListener!=null)GEvent.removeListener(mapRCListener);
			mapLCListener=GEvent.addListener(map, 'click', mapClick);
			mapRCListener=GEvent.addListener(map, 'singlerightclick', deleteLastPoint);
		}
		else if(armodify>0)
		{
			if(mapRCListener!=null)GEvent.removeListener(mapRCListener);
			mapRCListener=GEvent.addListener(map, 'singlerightclick', function(pixel)
				{
					mapCenter = map.fromContainerPixelToLatLng(pixel);
					{
						if(mapCenter!=null)
						{
							map.setCenter(mapCenter);
		        			showMarker(mapCenter, 0);
						}
					}
				});
		}
	}
	
	return false;
}

function RoutePoint(lat, lon, time, hr, distance)
{
	this.hr = hr;
	this.lat = lat;
	this.lon = lon;
	this.time = time;
	this.distance = distance;
	this.getLat = function(){return lat;};
	this.getLon = function(){return lon;};
	this.getLatLon = function(){return new GLatLng(lat,lon);};
	this.getTime = function(){return time;};
	this.getDistance = function(){return distance;};
	this.getHr = function(){return hr;};
}

var routePoints = [], lapPoints = [], marker;
var lineColor = "#ff0000", opacity = .5, lineWeight = 3;
var kmlFillColor = "7dff0000";
function mapClick(marker, clickedPoint)
{
	//alert("mapClick");
	if(clickedPoint==null)return;
	if(routePoints.length>=5000)
	{
		alert(strTooManyLatLonPoints1 + routePoints.length + strTooManyLatLonPoints2);
		return;
	}
	var t = 5000*routePoints.length;
	routePoints.push( new RoutePoint(clickedPoint.lat(), clickedPoint.lng(), t, 0) );
	drawCoordinates();
    calcGpsDistance(routePoints, true);
}
function clearMap(){map.clearOverlays();routePoints = [];lapPoints = [];drawCoordinates();calcGpsDistance(routePoints,true);}
function deleteLastPoint(){routePoints.pop();drawCoordinates();calcGpsDistance(routePoints,true);}

var routePlayPoints = [],routePlaySpeed,playing=false;
function playRoute(speed)
{
    if(routePlayTimer!=null)
    {
    	clearTimeout(routePlayTimer);routePlayTimer=null;
    }
    else if(!playing)
    {
    	routePlaySpeed=speed;
		routePlayPoints = [];
		if(routePoints.length<2)return;
		
		playStep = Math.ceil(routePoints.length / 200);
		if(playStep==0) playStep=1;
	    map.clearOverlays();
	    
	    var sm = new GMarker(routePoints[0].getLatLon(), {icon:starticon,title:'START'});
	    map.addOverlay(sm);
	
	    lastDist=0;lastTime=0;lastLapIcon=0;lastLapTime=0;
	    drawRoutePoint(0);
	    playing=true;
    }
    else 
    {
    	routePlayTimer = setTimeout("drawRoutePoint(" + (playIndex+1) + ");", 0);
    }
    	
}
/*function pauseRoute()
{
    if(routePlayTimer!=null){clearTimeout(routePlayTimer);routePlayTimer=null;}
    else routePlayTimer = setTimeout("drawRoutePoint(" + (playIndex+1) + ");", 0); 
}*/
function stopRoute()
{
	playing=false;
    if(routePlayTimer!=null)
    {
    	clearTimeout(routePlayTimer);routePlayTimer=null;
    }

	//drawCoordinates();
    calcGpsDistance(routePoints, true);
}
var routePlayTimer,lastDist,lastTime,lastLapTime,lastLapIcon,playIndex,cpMarker;
function decimalToHexString(number)
{
    if (number < 0){number = 0xFFFFFFFF + number + 1;}
    return number.toString(16).toUpperCase();
}
//function to generate the hex code
function getHex(dec)
{
var hexArray = new Array( "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B","C", "D", "E", "F" );
var code1 = Math.floor(dec / 16);
var code2 = dec - code1 * 16;
var decToHex = hexArray[code2];
return (decToHex);
}
function toHexCode(dec)
{
if(dec==0) return "00";
if(dec==255) return "FF";
var hexCode= new Array(),i=0;
while(dec > 15)
{
hexCode[i] = getHex(dec);
dec = Math.floor(dec / 16);
i+=1;
}

hexCode[i] = getHex(dec);
var decToHex = "";
for(i=hexCode.length-1; i>=0; i--){decToHex += hexCode[i];}
if(decToHex.length<2) decToHex = "0" + decToHex;
return decToHex;
}
function drawRoutePoint(index)
{
	if(cpMarker!=null) map.removeOverlay(cpMarker);
	
	playIndex=index;
	routePlayPoints.push(routePoints[index]);
	var curIndex = routePlayPoints.length-1;
	if(curIndex>0)
	{
	    var routeGLatLngPoints = new Array(2);
	    var lw=3;
	    for(var i=curIndex-1; i<=curIndex; i++)
	    	{
	    	routeGLatLngPoints.push(routePlayPoints[i].getLatLon());
	    	}
	    var hr = routePlayPoints[curIndex].getHr();
	    //alert('hr='+hr+", routePlayPoints[i].getLatLon()="+routePlayPoints[i].getLatLon());
	    var op = 0.8;//255;
	    var line = new GPolyline(routeGLatLngPoints,getColor(hr),lw,op);
	    map.addOverlay(line);

	    if(index<routePoints.length-1)
	    {
	    	if(hr>0)
	    	{
	    		if(hr>anaK) cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:maxicon});
	    		else if(hr>aerK) cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:anaicon});
	    		else cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:aericon});
	    	}
	    	else cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:aericon});
//	    	else if(index < (routePoints.length/3.0)) cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:aericon});
//	    	else if(index < (routePoints.length/1.5)) cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:anaicon});
//	    	else cpMarker = new GMarker(routePlayPoints[curIndex].getLatLon(), {icon:maxicon});
	    }
	    else cpMarker = addMarker(routePlayPoints[curIndex], 2);
	    map.addOverlay(cpMarker);
	    routeGLatLngPoints.pop();routeGLatLngPoints.pop();
	}
	
    var dist = calcGpsDistance(routePlayPoints,false);
    var time = routePlayPoints[curIndex].getTime() * 1.0;
    var delay = (time-lastTime) / routePlaySpeed;
    if(delay==0) delay = 1000*(dist-lastDist);
    if(delay>500)delay=500;
    lastDist = dist;lastTime=time;

    //add lap points
    if(lapPoints!=null)
    {
    	if(lapPoints.length>0 && lastLapIcon<lapPoints.length)
    	{
			var lt=lapPoints[lastLapIcon].getTime() * 1.0;
			if( lt<time)
			{
				addMarker(lapPoints[lastLapIcon],1);
    		    lastLapIcon++;
    		    lastLapTime+=lt;
			}
    	}
    }

    if(index<routePoints.length-1)
    {
        if(routePlayTimer!=null) clearTimeout(routePlayTimer);
        var nextIndex = index + playStep;
        if(nextIndex>routePoints.length-1) nextIndex=routePoints.length-1;
        routePlayTimer = setTimeout("drawRoutePoint(" + nextIndex + ");", delay); 
    }
    else
    {
    	stopRoute();
	    }    
}
var pminhr,pmaxhr;
function getColor(hr)
{
	var red=0,green=0,blue=0;
	var hrsteps = (255.0 / (pmaxhr-pminhr));
	
	var restToAnaK = anaK - pminhr;
	var r2af = 220.0/restToAnaK;
	
	red = (hr-pminhr) * r2af; if(red>220)red=220; if(red<0)red=0;
	red = Math.round(red);

	var aerKToAnaK = pmaxhr-aerK;//anaK - aerK;
	var a2af = 165.0/aerKToAnaK;

	var hrMaerK = hr-aerK; if(hrMaerK<0) hrMaerK=0;
	green = 165 - hrMaerK * a2af; if(green>165)green=165;if(green<0)green=0;
	green = Math.round(green);
	
    var hrcolor = "#" + toHexCode(red) + toHexCode(green) + toHexCode(blue);
    return hrcolor;
}
function addMarker(point,type)
{
	var marker;
	var dist=point.getDistance()/1000.0;
	dist = dist.toFixed(2);
	var lt=point.getTime() * 1.0;
	var h=Math.floor(lt/3600000),min=Math.floor((lt%3600000)/60000);
	var s=(lt-(3600000*h+60000*min))/1000.0;

	//start marker
	if(type==0) marker = new GMarker(point.getLatLon(), {icon:starticon,title:dist+'km'+" - "+h+":"+addLeadingZero(min,2)+":"+addLeadingZero(Math.round(s), 2)});
	//lap marker
	else if(type==1) marker = new GMarker(point.getLatLon(), {icon:lapicon,title:dist+'km'+" - "+h+":"+addLeadingZero(min,2)+":"+addLeadingZero(Math.round(s), 2)});
	//end marker
	else if(type==2)
	{
		marker = new GMarker(point.getLatLon(), {icon:endicon,title:dist+'km'+" - "+h+":"+addLeadingZero(min,2)+":"+addLeadingZero(Math.round(s), 2)});
	}
    map.addOverlay(marker);
    return marker;
}
function drawCoordinates()
{
	//alert("drawCoordinates");
    map.clearOverlays();
	var ri = document.getElementById("routeinfo");
	if(ri!=null)ri.innerHTML = "";

    if(routePoints==null)return;
    if(routePoints.length==0)return;
    
	//create route again
    var routeGLatLngPoints = new Array(routePoints.length);
    for(var i=0; i<routePoints.length; i++) routeGLatLngPoints.push(routePoints[i].getLatLon());
    woRouteLine = new GPolyline(routeGLatLngPoints,lineColor,lineWeight,opacity);
    map.addOverlay(woRouteLine);
//    if(routePoints.length>1)
//    {
//	    for(var i=1; i<4; i++)
//	    {
//	    	var routeGLatLngPoints = new Array(2);
//	    	alert("P1");
//	    	routeGLatLngPoints.push(routePoints[i-1].getLatLon());
//	    	alert("P2");
//	    	routeGLatLngPoints.push(routePoints[i].getLatLon());
//		    var hr = routePoints[i].getHr(),op = 255,lw=2;
//		    var line = new GPolyline(routeGLatLngPoints,getColor(hr),lw,op);
//		    map.addOverlay(line);
//	    	alert("P3");
//	    	//routeGLatLngPoints.pop();routeGLatLngPoints.pop();
//	    }
//    }
    
    startmarker = new GMarker(routePoints[0].getLatLon(), {icon:starticon,title:'START'});
    map.addOverlay(startmarker);
    if(routePoints.length>1)
    {
	    endmarker = new GMarker(routePoints[routePoints.length -1].getLatLon(), {icon:endicon,title:'FINISH'});
	    map.addOverlay(endmarker);
    }
    //add lap points
    if(lapPoints!=null)
    {
    	if(lapPoints.length>0)
    	{
    		for(var i=0; i<lapPoints.length; i++){addMarker(lapPoints[i],1);}
    	}
    }
}
function saveRoute()
{
	//alert("saveRoute");
	var kml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
		"<kml xmlns=\"http://earth.google.com/kml/2.1\">\n" +
		"<Document><name>Your name of document</name><description>Your description</description>\n" +
		"<Placemark>" +
		"<Style>\n<LineStyle><width>" + lineWeight + "</width></LineStyle>\n<PolyStyle><color>" + 
		kmlFillColor +"</color></PolyStyle>\n</Style>\n";
	
	kml += "<LineString><tessellate>1</tessellate>\n<coordinates>\n";
	
	if(routePoints.length>5000)
	{
		alert(strTooManyLatLonPoints1 + routePoints.length + strTooManyLatLonPoints2);
		return;
	}
	for (var i = 0; i<(routePoints.length); i++)
	{
		var lat = routePoints[i].getLat();
		var lon = routePoints[i].getLon();
		kml += lon + "," + lat + ",0\n";
	}
	kml += "</coordinates></LineString></Placemark>\n</Document>\n</kml>";

	//routename
	var rn = document.getElementById("routename").value;
	
	//using post so we must not urlencode the params!
	//alert(rn);
	var params = "action=gethrd&edited=1&u=" + userId + "&rn=" + rn + "&hrgpsid=" + (-newestHrGpsId) + "&kml=" + kml;
	hrxmlhttp = createXmlAjaxRequest("ajaxhrdata", params, hrDialogResponseHandler);
}
function calcGpsDistance(points, updateDistance)
{
	//alert("calcGpsDistance");
	if(points==null)return 0;
	if(points.length<2)
	{
		if(updateDistance) document.getElementById("sublength0").value = 0;
		return 0;
	}
	var R = 6371; // km
	
	var lat1,lat2,lon1,lon2;
	
	var dist = 0.0;
	for(var i=1; i<points.length;i++)
	{
		lat1 = points[i-1].getLat();
		lon1 = points[i-1].getLon();
		lat2 = points[i].getLat();
		lon2 = points[i].getLon();

		var dLat = toRad(lat2-lat1);
		var dLon = toRad(lon2-lon1); 

		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
		        Math.sin(dLon/2) * Math.sin(dLon/2); 
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var d = R * c;
		dist += d;
	}
	if(updateDistance) document.getElementById("sublength0").value = dist.toFixed(2);
	var ri = document.getElementById("routeinfo");
	if(ri!=null)ri.innerHTML = strDistance + ": " +  dist.toFixed(2) + " km (" + points.length + " " + strRoutePoints + ")";
	return dist;
}
function toRad(dec){return(dec*(Math.PI/180));}
function showMarker(point, z)
{
	//alert("showMarker");
	map.clearOverlays();
	if(z>0) map.setZoom(z);
	map.panTo(point);
	map.addOverlay(new GMarker(point, {draggable: false}));

	document.getElementById("latitude").value = point.lat().toFixed(8);
	document.getElementById("longitude").value = point.lng().toFixed(8);
}

function editRoute()
{
	//alert("editRoute");
	closeHrAttachDialog();
	showMap(1, 'mapdiv', 'mapcanvas', 'location', '1', true);
	//zoomMap(1, 1);
}

var starticon,aericon,anaicon,maxicon,lapicon,endicon;
function createIcons()
{
	starticon = new GIcon(),aericon = new GIcon(),anaicon = new GIcon(),maxicon = new GIcon(),lapicon = new GIcon(),endicon = new GIcon();

	//starticon.image = 'http://www.google.com/mapfiles/dd-start.png';
	starticon.image = 'http://www.trainit.fi/img/starticon.png';
	aericon.image = 'http://www.trainit.fi/img/aericon.png';
	anaicon.image = 'http://www.trainit.fi/img/anaicon.png';
	maxicon.image = 'http://www.trainit.fi/img/maxicon.png';
	lapicon.image = 'http://www.trainit.fi/img/lapicon.png';
	endicon.image = 'http://www.trainit.fi/img/endicon.png';
	
	starticon.iconSize = new GSize(16,16);starticon.iconAnchor = new GPoint(8,8);
	aericon.iconSize = new GSize(16,16);aericon.iconAnchor = new GPoint(8,8);
	anaicon.iconSize = new GSize(16,16);anaicon.iconAnchor = new GPoint(8,8);
	maxicon.iconSize = new GSize(16,16);maxicon.iconAnchor = new GPoint(8,8);
	lapicon.iconSize = new GSize(16,16);lapicon.iconAnchor = new GPoint(8,8);
	endicon.iconSize = new GSize(16,16);endicon.iconAnchor = new GPoint(8,8);
}
var woRouteLine;
function createPolyline(points){woRouteLine = new GPolyline( points , "#af0000", 4);}
var anaK,aerK;
function showWorkoutRoute()
{
	//alert("showWorkoutRoute");
	if (GBrowserIsCompatible())
	{
		document.getElementById(mapCanvasName).style.display="block";

		if(map==null)
		{
		    var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
		    copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));
			var tilesMapnik = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
			var mapMapnik = new GMapType([tilesMapnik],G_NORMAL_MAP.getProjection(), "OSM");
			map = new GMap2(document.getElementById(mapCanvasName), { mapTypes: [mapMapnik, G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP, G_PHYSICAL_MAP] });
			//map = new GMap2(document.getElementById(mapCanvasName));
			//map.addMapType(G_PHYSICAL_MAP);//map.addMapType(G_AERIAL_HYBRID_MAP);			

			map.addControl(new GSmallZoomControl3D(100)); 
			map.addControl(new GMapTypeControl());
			
			createIcons();
		}
		map.getDragObject().setDraggableCursor("default");
		if(mapLCListener!=null)GEvent.removeListener(mapLCListener);
		if(mapRCListener!=null)GEvent.removeListener(mapRCListener);
		mapLCListener=GEvent.addListener(map, 'click', mapClick);
		mapRCListener=GEvent.addListener(map, 'singlerightclick', deleteLastPoint);
		
		drawCoordinates();
		if(woRouteLine!=null)
		{
			var bounds=woRouteLine.getBounds();
			mapCenter = new GLatLng(bounds.getCenter().lat(),bounds.getCenter().lng());
			map.setCenter( mapCenter, map.getBoundsZoomLevel( bounds ) );
		}
	}
	return false;
}
function hideWorkoutRoute(){document.getElementById(mapDivName).style.display="block";document.getElementById(mapCanvasName).style.display="none";document.getElementById("routeeditdiv").style.display = "none";}
/********** Google maps functionality **********/



//upload hrm file to database
function uploadHrFile()
{
	var dlg = document.getElementById("hrgpsdlg");if(dlg!=null)dlg.style.cursor = "wait";
	var lst=document.getElementById("hrgpsidlist");if(lst!=null)lst.style.cursor = "wait";
	var parentForm = document.getElementById("uploadfile");
	if(parentForm!=null)
	{
		parentForm.target = 'upload_target';
		parentForm.submit();
		hrultimercount=0;
		setTimeout("hrUploadTimer()", 4000);
	}
	return false;
}
var hrultimer;
var hrultimercount;
function hrUploadTimer()
{
	getHrGpsGraph(-newestHrGpsId);//get last hr graph
	if(hrultimer) clearTimeout(hrultimer);
	if(hrultimercount<10)
	{
		hrultimer=setTimeout("hrUploadTimer();",4000);
		hrultimercount++;
	}
	else
	{
		alert(strHrGpsDataUploadFailed);
		var dlg = document.getElementById("hrgpsdlg");if(dlg!=null)dlg.style.cursor = "default";
		var lst=document.getElementById("hrgpsidlist");if(lst!=null)lst.style.cursor = "default";
	}
}


function calculateHRZones()
{
	//zone name fields
	var zonename0 = document.getElementById('zonename0');
	var zonename1 = document.getElementById('zonename1');
	var zonename2 = document.getElementById('zonename2');
	var zonename3 = document.getElementById('zonename3');
	var zonename4 = document.getElementById('zonename4');
	zonename0.value = strMaxZone;
	zonename1.value = strMKZone;
	zonename2.value = strVKZone;
	zonename3.value = strPKZone;
	zonename4.value = strEKZone;

	// harjoitussyke = (maksimisyke-leposyke) x harjoitusteho % + leposyke
	// zone lower limit fields
	var lowerlimit0 = document.getElementById('lowerlimit0');
	var lowerlimit1 = document.getElementById('lowerlimit1');
	var lowerlimit2 = document.getElementById('lowerlimit2');
	var lowerlimit3 = document.getElementById('lowerlimit3');
	var lowerlimit4 = document.getElementById('lowerlimit4');
	var maxhr = document.getElementById('maxhr').value *1.0;
	var minhr = document.getElementById('resthr').value * 1.0;
	var maxmin = maxhr - minhr;
	
	lowerlimit0.value = ((maxmin * 0.95) + minhr).toFixed(0);
	lowerlimit1.value = ((maxmin * 0.85) + minhr).toFixed(0);
	lowerlimit2.value = ((maxmin * 0.70) + minhr).toFixed(0);
	lowerlimit3.value = ((maxmin * 0.50) + minhr).toFixed(0);
	lowerlimit4.value = ((maxmin * 0.35) + minhr).toFixed(0);
	
	calculateUpperLimits();
}

function calculateUpperLimits()
{
	//get max hr
	var maxhr = document.getElementById('maxhr').value *1.0;
	var upperlimit0 = document.getElementById('upperlimit0');
	upperlimit0.innerHTML = maxhr;
	
	// other upper limits
	for(var i=1; i<5; i++)
	{
		var prevlower = document.getElementById('lowerlimit'+(i-1));
		var ulfield = document.getElementById('upperlimit'+i);
		ulfield.innerHTML = prevlower.value;
	}
}











var subFoodIndex=-1;
var selectedIndex=-1;
var selectedSearchField=-1;
var fsxmlhttp;

// array of arrays that stores nutrients of subfoods
var subFoodData = null;
// array of arrays that stores current foodlist's food's nutrients
var foodListData = null;

function createSubFoodDataArray(count)
{
	subFoodData = new Array(count);
	for(var i=0; i<count; i++)
	{
		subFoodData[i] = new Array(5);
	}
}
function eatingResponseHandler()
{
	if(fsxmlhttp==null) return false;
	
	if (fsxmlhttp.readyState==4 && fsxmlhttp.status==200)
	{
		var index = subFoodIndex;
		var fl = fsxmlhttp.responseXML.getElementsByTagName("foodlist")[0];
		
		if(fl==null)
		{
			var fieldId = "foodsearch" + index; 
			var field = document.getElementById(fieldId);
			field.style.color = "#ff0000";
			field.style.textDecoration = "line-through";
			hideFoodList();
			return false;
		}
			
		var htmlStr = "<div id=\"foodinnerlist\" class=\"foodlist\" style=\"background-color:#ffffff;border: 1px solid #000000;padding:3px;\">";
		var fb = fl.getElementsByTagName("foodbean");
		foodListData = new Array(fb.length);
		for(var i=0; i<fb.length; i++)
		{
			var food = fb[i];
			var id = food.getAttribute("id");
			var name = food.getAttribute("name");
			var energy = food.getAttribute("e");
			var p = food.getAttribute("p");
			var h = food.getAttribute("h");
			var f = food.getAttribute("f");
			var po = food.getAttribute("po");
			var un = food.getAttribute("un");
			var portion = food.getAttribute("prt");
			
			htmlStr += "<div class=\"foodlistrow\" onClick=\"foodClicked(" + i + ")\">";
			htmlStr += "<span class=\"foodlistitem_left\" id=\"fooditem" + i + "\">" + name + "</span>";
			htmlStr += "<span class=\"foodlistitem_left\">" + energy + " kcal/100g</span>";
			
			var id2 = id.substring(4);
			var zeros = "00000";
			var l = id2.length;
			var portionStr = "";
			if(portion!="0.0") portionStr = strOnePortion + "=" + portion + "g";
			htmlStr += "<span class=\"foodlistitem_left\">" + portionStr + "</span>";
			
			if(id2>20000)
				htmlStr += "<span class=\"foodlistitem_right\">[" + un + "]</span>";
			else if(id2>10000)
				//htmlStr += "<span class=\"foodlistitem_right\">[lmv" + zeros.substring(0, 5-l) + id2 + "]</span>";
				htmlStr += "<span class=\"foodlistitem_right\">[lmv]</span>";
			else
				//htmlStr += "<span class=\"foodlistitem_right\">[tra" + zeros.substring(0, 5-l) + id2 + "]</span>";
				htmlStr += "<span class=\"foodlistitem_right\">[tra]</span>";
			htmlStr += "</div>";
			
			// store nutrients of foods in list
			foodListData[i] = new Array(5);
			foodListData[i][0] = id;
			foodListData[i][1] = energy;
			foodListData[i][2] = h;
			foodListData[i][3] = p;
			foodListData[i][4] = f;						
			foodListData[i][5] = po;						
		}
		htmlStr += "<div class=\"foodlistrowlast\" onClick=\"\">";
		
		htmlStr += "<span class=\"foodlistitem_left\"><a href=\"javascript:createAddFoodDialog('foodsearch" + selectedSearchField + "')\" style=\"\">" + strAddNewFood + "</a></span>";
		htmlStr += "<span class=\"foodlistitem_right\"><a href=\"javascript:hideFoodList();\">" + strClose + "</a></span>";
		htmlStr += "</div>";
		
		setSubFoodData(index, -1, 0, 0, 0, 0, 0);
		if(htmlStr!=null)
		{
			var fieldId = "foodsearch" + index; 
			var field = document.getElementById(fieldId);
			if(htmlStr.length>0)
			{
				createList(field);
				var list = document.getElementById("foodouterlist");
				list.innerHTML=htmlStr;
				var listdiv = list.childNodes.item(0);
				
				var count = listdiv.childNodes.length;
				if(count>2)
				{
					field.style.textDecoration = "none";
					field.style.color = "#000000";
				}
				else if(count==2)
				{
					field.style.textDecoration = "none";
					field.style.color = "#008000";
					currentrow = listdiv.childNodes.item(0);
					selectedIndex = 0;
					setFood(currentrow, selectedSearchField, selectedIndex);
					hideFoodList();
				}
				else
				{
					field.style.color = "#ff0000";
					field.style.textDecoration = "line-through";
					hideFoodList();
				}
			}
			else
			{
				field.style.color = "#ff0000";
				field.style.textDecoration = "line-through";
				hideFoodList();
			}
		}
		else
		{
			field.style.color = "#ff0000";
			field.style.textDecoration = "line-through";
			hideFoodList();
		}
		return true;
	}
}
function setFood(currentrow, searchindex, itemindex)
{
	if(selectedIndex>-1)
	{
		currentrow.setAttribute("class", "foodlistrow_selected");
		var foodsearch = document.getElementById("foodsearch"+searchindex);

		var v = currentrow.childNodes.item(0).innerHTML;
		v = v.replace(/&lt;/ig, '<');
		v = v.replace(/&gt;/ig, '>');
		v = v.replace(/&amp;/ig, '&');
		v = v.replace(/&quot;/ig, '\"');
		v = v.replace(/&apos;/ig, '\'');

		foodsearch.value = v;
		foodsearch.style.textDecoration = "none";
		foodsearch.style.color = "#008000";
		foodsearch.title = currentrow.childNodes.item(0).innerHTML + " " + currentrow.childNodes.item(1).innerHTML;
		
		var subfoodid = document.getElementById("subfoodid"+searchindex);
		subfoodid.value = foodListData[itemindex][0].substring(4);
		
		// set default value for portion/gram selection
		var pgsel = document.getElementById("subunit"+searchindex);
		if(foodListData[itemindex][5]==0)
		{
			pgsel.selectedIndex = 1;
			pgsel.options[0].disabled = true;
		}
		else
		{
			pgsel.options[0].disabled = false;
			pgsel.selectedIndex = 0;
		}



		//set new nutrient values
		subFoodData[searchindex][0] = foodListData[itemindex][1];
		subFoodData[searchindex][1] = foodListData[itemindex][2];
		subFoodData[searchindex][2] = foodListData[itemindex][3];
		subFoodData[searchindex][3] = foodListData[itemindex][4];
		subFoodData[searchindex][4] = foodListData[itemindex][5];
	}
	else
	{
		//setSubFoodData(index, -1, 0, 0, 0, 0);
	}
	calculateTotalSum();
}
//called from java
function setSubFoodData(index, foodid, cal100g, carbons, proteins, fat, portion)
{
	var cfoodid = document.getElementById("subfoodid"+index);
	cfoodid.value = foodid;
	subFoodData[index][0] = cal100g;
	subFoodData[index][1] = carbons;
	subFoodData[index][2] = proteins;
	subFoodData[index][3] = fat;
	subFoodData[index][4] = portion;
	// calculateTotalSum();
}
function searchFieldKeyPress(e, field, index)
{
	return false;
}
function foodClicked(index)
{	
	if(index<0) return false;
	var currentrow;
	if(selectedIndex>-1)
	{
		currentrow = document.getElementById("foodinnerlist").childNodes.item(selectedIndex);
		if(currentrow!=null)
		{
			currentrow.setAttribute("class", "foodlistrow");
		}
	}
	selectedIndex = index;
	currentrow = document.getElementById("foodinnerlist").childNodes.item(selectedIndex);
	setFood(currentrow, selectedSearchField, selectedIndex);
	hideFoodList();
	return false;
}
function searchFieldKeyDown(e, field, index)
{
	if(e.keyCode == 13 || e.keyCode == 9)
	{
		hideFoodList();
		return false;
	}
	else if(e.keyCode == 40 || e.keyCode == 38)
	{					
		var id = "foodinnerlist";
		var currentrow;
		if(selectedIndex>-1)
		{
			currentrow = document.getElementById(id).childNodes.item(selectedIndex);
			if(currentrow!=null)
			{
				currentrow.setAttribute("class", "foodlistrow");
			}
		}

		var items = document.getElementById(id).childNodes.length;
		if(e.keyCode == 40)// DOWN
		{
			if(selectedIndex == items-2) selectedIndex = -1;
			else if(selectedIndex<items-2) selectedIndex++;
		}
		else if(e.keyCode == 38)// UP
		{
			if(selectedIndex>-1) selectedIndex--;
			else selectedIndex = items-2;
		}
		
		if(selectedIndex>-1)
		{
			currentrow = document.getElementById("foodinnerlist").childNodes.item(selectedIndex);
			setFood(currentrow, selectedSearchField, selectedIndex);
		}
		return false;
	}
}
function searchFieldKeyUp(e, field, index)
{
	// ENTER or TAB
	if(e.keyCode == 13 || e.keyCode == 9)
	{
		hideFoodList();
		return false;
	}
	//special characters
	// if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode ==
	// 40 || e.keyCode==17 || e.ctrlKey)
	else if(e.keyCode<48 && e.keyCode!=8 && e.keyCode!=46)
	{
		//alert("40, 38 tai CTRL");
		return false;
	}
	//normal
	else
	{
		selectedIndex=-1;
		selectedSearchField=index;
		searchFood(field, index);
		return false;
	}
}
function searchFood(field,index)
{
	selectedSearchField = index;
	selectedIndex = -1;

	var word = field.value;
	if(word!=null)
	{
//		alert("word!=null="+word);
		if(word.length>0)
		{
			//alert("word.length="+word.length);
			//word = word.replace('*', '_');
			word = word.replace(/%/ig, '_');
			word = word.replace(/&/ig, '_');
			word = word.replace(/-/ig, '_');
			word = word.replace(/ /ig, '_____');
			word = word.replace(/[^a-zåäöèê0-9_ .,;'()=\/\\]/ig, '');

			// var tms = new Date().getTime();
			// var request = "foodsearch?keyword=" + word + "&tms=" + tms;
			var sfuf = document.getElementById("sfuf");
			var sfufvalue = "";
			if(sfuf.checked==true) sfufvalue="sfuf";
			var request = "foodsearch?action=search&keyword=" + encodeURIComponent(word) + "&sfuf=" + sfufvalue;
			//alert(request);
			subFoodIndex = index;
			fsxmlhttp = createAjaxRequest(request, eatingResponseHandler);
		}
		else
		{
			field.style.textDecoration = "none";
			field.style.color = "#000000";
			hideFoodList();
			setSubFoodData(index, -1, 0, 0, 0, 0, 0);
		}
	}
	else
	{
		hideFoodList();
		setSubFoodData(index, -1, 0, 0, 0, 0, 0);
	}
}
function getFoodData(field,index)
{
}


String.prototype.startsWith = function(str)
{
	if(this.match(str)) return true;
	else return false;
}
String.prototype.trim = function()
{
	return	(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

function searchFieldOnFocus(field, index)
{
	var str = "";
	str = field.value;
	if(str.startsWith("--") || str.startsWith(" - -"))
	{
		clearSearchText(field);
	}
}
function searchFieldOnBlur(field, index)
{
	//alert("searchFieldOnBlur");
	// hideFoodList();
}
function hideFoodList()
{
	var list = document.getElementById("foodouterlist");
	if(list!=null)
	{
		list.innerHTML = '';
		list.style.visibility = "hidden";
	}
	calculateTotalSum();
}

function clearSearchText(field)
{
	field.value = '';
}			
function clearFoodList(id)
{
	document.getElementById(id).innerHTML = '';	
}


function createList(parent)
{				
 	var x = parent.offsetLeft;// + parent.width;
 	var y = parent.offsetTop + parent.offsetHeight;// + parent.height;

 	// deal with elements inside tables and such
 	var p = parent;
 	while (p.offsetParent) 
 	{
 		p = p.offsetParent;
 	    if(p.offsetLeft>0) x += p.offsetLeft;
 	    if(p.offsetTop>0) y += p.offsetTop;
 	}
 	if( (x+300)>document.body.offsetWidth){x-=300;}
 	if(y<0) y=50;

	var objectId = "foodouterlist";
	var object = document.getElementById(objectId);
	if (!object) 
	{
		object = document.createElement("div");
		object.setAttribute("id", objectId);
		//object.setAttribute("class", "foodlist");
		//object.setAttribute("style", "visibility: visible;width:355px;border: 1px solid #000;");
		document.body.appendChild(object);
	}
	object.style.position = "absolute";
	object.style.left = x + "px";
	object.style.top = y + "px";
	object.style.visibility = "visible";
	object.style.display = "block";
	object.style.zIndex = 10000;
	object.style.width = "600";
	object.style.height = "auto";
}









/*Eating calculations*/
var jsfoods = new Array();
var jscarbons=new Array();
var jsproteins=new Array();
var jsfat=new Array();
var num_of_subs=0;
function calculateTotalSum()
{
	try
	{
	var total=0;
	var totalCarbons=0;
	var totalProteins=0;
	var totalFat=0;
	var totalWeight=0;

	var iter=0;
	for(iter=0; iter<num_of_subs; iter++)
	{
		var wf = document.getElementById('subweight'+iter);
		var unitsel = document.getElementById('subunit'+iter);
		var realweight = document.getElementById('realweight'+iter);
		var unit = unitsel.value;
		// alert(unit);
		var w = wf.value;
		if(w==null || w=="") w=0;
		else w = w.replace(/,/ig, '.');
		var weight = w;
		var index = iter;
		
		// var energy = jsfoods[selectedIndex];
		var cal100g = subFoodData[index][0];
		var portion = subFoodData[index][4];
			

		// alert(portion);
		if(unit==0)
		{
			//alert(unit);
			weight = (weight * portion);
		}
		
		var carbons = (subFoodData[index][1]*weight)/100;
		var proteins = (subFoodData[index][2]*weight)/100;
		var fat = (subFoodData[index][3]*weight)/100;
		var fat = (subFoodData[index][3]*weight)/100;

		var lblCal100g = document.getElementById('cal100g'+iter);
		var lblCal = document.getElementById('calories'+iter);
		var lblCarbons = document.getElementById('carbons'+iter);	
		var lblProteins = document.getElementById('proteins'+iter);	
		var lblFat = document.getElementById('fat'+iter);	
		if(weight>0)
		{
			var cals = (cal100g*weight)/100;
			total = total + cals;
			realweight.innerHTML = (weight*1.0).toFixed(1);
			lblCarbons.innerHTML = carbons.toFixed(1);
			lblProteins.innerHTML = proteins.toFixed(1);
			lblFat.innerHTML = fat.toFixed(1);
			lblCal100g.innerHTML = cal100g;
			lblCal.innerHTML = cals.toFixed(1);
			totalCarbons = totalCarbons + carbons;
			totalProteins = totalProteins + proteins;
			totalFat = totalFat + fat;
			totalWeight = totalWeight + weight*1.0;
		}
		else
		{
			realweight.innerHTML = "";
			lblCarbons.innerHTML = "";
			lblProteins.innerHTML = "";
			lblFat.innerHTML = "";
			lblCal100g.innerHTML = "";
			lblCal.innerHTML = "";
		}
	}
	var sumWeight = document.getElementById('totalWeight');	
	sumWeight.innerHTML = totalWeight.toFixed(1);

	var sum = document.getElementById('totalSum');	
	sum.innerHTML = total.toFixed(1);

	var sumCarbons = document.getElementById('totalCarbons');	
	sumCarbons.innerHTML = totalCarbons.toFixed(1);
	var sumProteins = document.getElementById('totalProteins');	
	sumProteins.innerHTML = totalProteins.toFixed(1);
	var sumFat = document.getElementById('totalFat');	
	sumFat.innerHTML = totalFat.toFixed(1);
	}catch(e){}
}
function foodChanged(row)
{
	calculateTotalSum();
}
function weightChanged(row,weight)
{
	calculateTotalSum();			
}




var addfoodxmlhttp;
function createAddFoodDialog(parentName)
{
	hideFoodList('foodlist');
	var parent = document.getElementById(parentName);
	
 	var bodyHeight = Math.max(document.body.offsetHeight, window.innerHeight);
 	var bodyWidth = document.body.offsetWidth;
 	var x = parent.offsetLeft;// + parent.width;
 	var y = parent.offsetTop + parent.offsetHeight;// + parent.height;

 	// deal with elements inside tables and such
 	var p = parent;
 	while (p.offsetParent) 
 	{
 		p = p.offsetParent;
 	    if(p.offsetLeft>0) x += p.offsetLeft;
 	    if(p.offsetTop>0) y += p.offsetTop;
 	}
 	if( (x+300)>document.body.offsetWidth){x-=300;}
 	if(y<0) y=50;

	var dialogid = "afdlg";
	var afdFrame = document.getElementById(dialogid);
	if (!afdFrame) 
	{
		afdFrame = document.createElement("div");
		afdFrame.setAttribute("id", dialogid);
		afdFrame.setAttribute("style", "visibility: hidden;");
		document.body.appendChild(afdFrame);
		
		var html = "<div style=\"background-color:#ffffff;border: 1px solid #000;\">"; 
		html += "<div id=\"title\" class=\"hrdatalist\" style=\"height:25px;padding:5px;margin:0;margin-bottom:20px;border: 1px solid #000;background-color:#B4C9C9;\">" +
				"<span style=\"float:left;\">" + strAddOwnFood + "</span>" +
				"<span style=\"float:right;\">" +
				"<a class=\"image\" title=\"" + strClose + "\" href=\"javascript:closeAddFoodDialog();\">" +
				"<img class=\"icon\" alt=\"X\" src=\"" + imgClose + "\"></a></span>" +
				"</div>";
	
		var strTable = "<div style=\"width:480px;margin-bottom:10px\">" + strAddFoodHelp + "</div>";
		strTable += "<table>";
		strTable += "<tr><td style=\"text-align:right;\"><b>" + strFoodName + "</b></td><td><input style=\"width:300px;\" id=\"nfname\" name=\"nfname\" class=\"inputlong\"></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\">" + strFoodDesc + "</td><td><TEXTAREA style=\"width:300px;height:80px;\" id=\"nfdesc\" name=\"nfdesc\" COLS=30 ROWS=3></TEXTAREA></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\">" + strFoodPortion + "</td><td><input id=\"nfport\" name=\"nfport\" class=\"inputfloat\"></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\"><b>" + strKcal100g + "</b></td><td><input id=\"nfkcal\" name=\"nfkcal\" class=\"inputfloat\"></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\">" + strCarbos + "</td><td><input id=\"nfcarb\" name=\"nfcarb\" class=\"inputfloat\"></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\">" + strProt + "</td><td><input id=\"nfprot\" name=\"nfprot\" class=\"inputfloat\"></td></tr>";
		strTable += "<tr><td style=\"text-align:right;\">" + strFat + "</td><td><input id=\"nffat\" name=\"nffat\" class=\"inputfloat\"></td></tr>";
		//strTable += "<tr><td>" + strAlc + "</td><td><input id=\"nfalc\" name=\"nfalc\" class=\"inputfloat\"></td></tr>";
		
		strTable += "<tr><td></td><td><input type=\"button\" class=\"jsbtn\" style=\"margin-bottom:20px;\" value=\"" + strSave + "\" " + "onclick=\"addFoodPressed('nfname', 'nfdesc', 'nfport', 'nfkcal', 'nfcarb', 'nfprot', 'nffat');return false;\" " + "accesskey=\"s\"></td></tr>";
		strTable += "</table>";
	
		html += strTable;
		html += "</div>";
		afdFrame.innerHTML = html;	
	}
	afdFrame.style.position = "absolute";
	afdFrame.style.left = x + "px";
	afdFrame.style.top = y + "px";
	afdFrame.style.visibility = (afdFrame.style.visibility == "visible" ? "hidden" : "visible");
	afdFrame.style.display = "block";
	afdFrame.style.zIndex = 10000;
	afdFrame.style.width = "500";
	afdFrame.style.height = "auto";
}
//close "dialog"
function closeAddFoodDialog()
{				
	var dialogid = "afdlg";
	var dialog = document.getElementById(dialogid);
	if(dialog!=null)
	{
		dialog.style.visibility = "hidden";
	}
}			



function addFoodPressed(nfname, nfdesc, nfport, nfkcal, nfcarb, nfprot, nffat)
{
	//alert("addFoodPressed("+nfname+", "+nfdesc+", "+nfkcal+", "+nfcarb+", "+nfprot+", "+nffat+")");
	var namefield = document.getElementById(nfname);
	var descfield = document.getElementById(nfdesc);
	var portfield = document.getElementById(nfport);
	var kcalfield = document.getElementById(nfkcal);
	var carbfield = document.getElementById(nfcarb);
	var protfield = document.getElementById(nfprot);
	var fatfield = document.getElementById(nffat);
	
	var request = "foodsearch?action=add&nfname=" + encodeURIComponent(namefield.value) + "&nfdesc=" + encodeURIComponent(descfield.value)
				+ "&nfport=" + encodeURIComponent(portfield.value) + "&nfkcal=" + encodeURIComponent(kcalfield.value) + "&nfcarb=" + encodeURIComponent(carbfield.value)
				+ "&nfprot=" + encodeURIComponent(protfield.value) + "&nffat=" + encodeURIComponent(fatfield.value);
	
	addfoodxmlhttp = createAjaxRequest(request, afResponseHandler);
	return false;
}
function afResponseHandler()
{
	if(addfoodxmlhttp==null) return;
	//alert("afResponseHandler()");
	if (addfoodxmlhttp.readyState==4)
	{
		var ownfood = addfoodxmlhttp.responseXML.getElementsByTagName("ownfood")[0];
		if(ownfood==null)
		{
			alert(strFoodCouldNotBeAdded);
		}
		else
		{
			var id = ownfood.getAttribute("id");
			if(id>0)
			{
				alert(strFoodWasAdded);
				closeAddFoodDialog();
			}
			else
			{
				alert(strFoodCouldNotBeAdded);
			}
		}
	}
}




/********** UTILITIES **********/
	function openUrlSB(e, url)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		window.location = url;
	}
	function goToUrl(url)
	{
		//alert("goToUrl("+url+")");
		window.location = url;
	}
	function openUrl(url)
	{
		//alert("openUrl("+url+")");
		window.location = url;
	}
	
	function encrypt(npw1,npw2)
	{
		var pw1 = document.getElementById(npw1);	
		var pw2 = document.getElementById(npw2);	
		var pw1_val = pw1.value; 
		var pw2_val = pw2.value;
		if(pw1_val.length>4 && pw2_val.length>4)
		{
			var epw1 = hex_sha1(pw1_val);
			var epw2 = hex_sha1(pw2_val);
			pw1.value = epw1;
			pw2.value = epw2; 
		}
	}
	function encryptLogin(login, pwd, rememberme)
	{
		var loginField = document.getElementById(login);
		var pwField = document.getElementById(pwd);

		var epw = pwField.value;
		if(!loginCookieFound) epw = hex_sha1(pwField.value);
		pwField.value = epw;

		var rememberCB = document.getElementById(rememberme);
		var saveCookie = rememberCB.checked;
		if(saveCookie>0)
		{
			createCookie('email',loginField.value, 30);
			createCookie('pw',epw, 30);
		}
	}
	
	/* Show or hide UI part*/
	function showTable(tableName)
	{
		var table = document.getElementById(tableName);
		if(table.style.display=="none")
		{
			table.style.display="block";
		}
		else
			table.style.display="none";
	}
	
	/* Show or hide UI part depending on checkbox state*/
	function switchVisibilityFromCB(cbName, compName)
	{
		var cb = document.getElementById(cbName);
		var comp = document.getElementById(compName);
		
		if(cb.checked)
		{
			comp.style.display="block";
		}
		else
		{
			comp.style.display="none";
		}
	}
	function getDate(isodate)
	{
		var dt = new Date();
		var y = isodate.substring(0,4);
		var m = isodate.substring(5,7)-1;
		var d = isodate.substring(8,10);
		dt.setFullYear(y,m,d);
		return dt;
	}
	function checkRepeatDay(fdow, startDayName, repeatDayBaseName)
	{
		//alert("checkRepeatDay");
		var startdaycomp = document.getElementById(startDayName);
		var dt = getDate(startdaycomp.value);
		var dayOfWeek = dt.getDay() + 1; //java: 1-7, JS: 0-6
		var index = fdow;
		for(var i=1; i<8; i++)
		{
			var daycomp = document.getElementById(repeatDayBaseName + index);
			//daycomp.checked = false;
			if(dayOfWeek==index) 
			{
				daycomp.checked=true;
			}
			index++;
			if(index>7) index=1;
		}		
	}
	function hideEventEndDateTime(repeatSelect, enddaterow, endtimerow)
	{
		var edr = document.getElementById(enddaterow);
		var etr = document.getElementById(endtimerow);
		if(repeatSelect.value==0)
		{
			if(edr!=null) edr.style.display="block";
			if(etr!=null) etr.style.display="block";
		}
		else //if(repeatSelect.value==7)
		{
			if(edr!=null) edr.style.display="none";
			if(etr!=null) etr.style.display="none";
		}
	}
	function showRepeat(repeatSelect, repeatDaysName, repeatEndName)
	{
		var dayscomp = document.getElementById(repeatDaysName);
		var endcomp = document.getElementById(repeatEndName);
		if(repeatSelect.value==0)
		{
			if(dayscomp!=null) dayscomp.style.display="none";
			if(endcomp!=null) endcomp.style.display="none";
		}
		else //if(repeatSelect.value==7)
		{
			if(dayscomp!=null) dayscomp.style.display="block";
			if(endcomp!=null) endcomp.style.display="block";
		}
//		else
//		{
//			if(dayscomp!=null) dayscomp.style.display="none";
//			if(endcomp!=null) endcomp.style.display="block";
//		}
	}
	function modifyAllRepeatedEvents(e,title,link, linkall)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();

		showDialog(e,strRepeatingEvent + title,
				'<p>' + strModifyAllRepeatingEvents + '</p>',
				'prompt',1,
				0,
				strAllRepeatingEvents,
				"goToUrl('"+linkall+"')",
				strOnlyThisEvent,
				"goToUrl('"+link+"')",
				null,
				null);
		return false;
	}
	function modifyAllRepeatedWorkouts(e,title,link, linkall)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();

		showDialog(e,strRepeatingWorkout + title,
				'<p>' + strModifyAllRepeatingWorkouts + '</p>',
				'prompt',1,
				0,
				strAllRepeatingWorkouts,
				"goToUrl('"+linkall+"')",
				strOnlyThisWorkout,
				"goToUrl('"+link+"')",
				null,
				null);
		return false;
	}
	function createButton(text,action)
	{
		var btn = document.createElement("BUTTON");
		var t = document.createTextNode(text);
		btn.appendChild(t);
		btn.setAttribute("class", "jsbtn");
		btn.className = "jsbtn";
		btn.style.margin = "10px";
		btn.Value = text;

		btn.onclick = new Function( action );
		return btn;
	}
	function showErrorDialog(error)
	{
		var timeout = 5;
		if(error!=null)
		{
			showDialog(null, "",
				'<p>' + error + '</p>',
				'info',0,
				timeout,
				strOK,
				"hideDialog()",
				null,
				null,
				null,
				null);
		}
		return true;
	}
	function showInfoDialog(msg)
	{
		var timeout = 3;
		if(msg!=null)
		{
			showDialog(null, "",
				'<p>' + msg + '</p>',
				'prompt',0,
				timeout,
				strOK,
				"hideDialog()",
				null,
				null,
				null,
				null);
		}
		return true;
	}
	function clearText(field)
	{
		field.value = '';
	}
	function textFieldOnClick(field, origstr)
	{
		if(origstr!=null)
		{
			if(field.value==origstr) field.value="";
		}
		field.focus();
		field.select();
	}
	function createCookie(name,value,days) 
	{
		if (days) 
		{
			var date = new Date();
			date.setTime(date.getTime() + (days*24*60*60*1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	}
	function readCookie(name) 
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) 
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) 
			{
				return c.substring(nameEQ.length, c.length);
			}
		}
		if(name == "email") return strEmailAddress;
		if(name == "pw") return "12345678";
		return null;
	}
	
	function eraseCookie(name) 
	{
		createCookie(name, "", -1);
	}
	function eraseLoginCookies() 
	{
		loginCookieFound=false;
		createCookie("email", "", -1);
		createCookie("pw", "", -1);
	}
	
	var loginCookieFound=false;
	function init()
	{
		var loginField = document.getElementById('account');
		var pwField = document.getElementById('password');
		loginField.value = readCookie('email');
		
		var pw = readCookie('pw');
		if(pw!="1234") loginCookieFound=true;
		pwField.value = pw;
	}
	function setElemHeight(elem, h) 
	{
		var element = document.getElementById('comment');
		element.style.height = h;
		element.height = h;
	}

	
	//peruskulutuksen laskeminen
	// Nainen = (7,18 * paino + 795) * aktiivisuus
	// Mies = (10,2 * paino + 879) * aktiivisuus

	// Nainen = (0.8 * (65 + 0.8*(paino-65)) * 24) * aktiivisuus
	// Mies = (1.0 * (80 + 0.8*(paino-80)) * 24) * aktiivisuus
	// 1.1 = Hyvin matala
	// 1.2 = Matala
	// 1.3 = Kohtuullinen
	// 1.4 = Korkea
	// 1.5 = Hyvin korkea
	function calculateBaseConsumption()
	{
		var sex0 = document.getElementById('bcsex0');
		var sex1 = document.getElementById('bcsex1');
			
		var length = document.getElementById('length');
		var weight = document.getElementById('bcweight');
		var activity = document.getElementById('bcactivity');
		
		var bc = 0;
		var l = length.value / 100.0;
		var w = weight.value;
		if(l==0 || w==0)
		{
			alert(strBCGiveYourLengthAndWeight);
			return;
		}
		var a = activity.value;
		
		var bmi = w / (l * l);
		var w_n = 25.0 * (l*l);
		
		// nainen
		if(sex0.checked)
		{
			bc = (w_n + 0.4*(w-w_n))*0.95*24*a/10;
		}
		//mies
		else if(sex1.checked)
		{
			bc = (w_n + 0.4*(w-w_n))*1.05*24*a/10;
		}

		var bcfield = document.getElementById('baseconsumption');
		bcfield.value = bc.toFixed(0);
	}

	
	function confirmDelete(link, question)
	{
		//alert("confirmDelete("+link+","+question+")");
		var answer = confirm(question);
		if (answer)
		{
			document.location = link;
		}
		return false;
	}
	function confirmDeleteSB(e, link, question)
	{
		//alert("confirmDeleteSB("+e+","+link+","+question+")");
		var answer = confirm(question);
		if (answer)
		{
			document.location = link;
		}
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();

		return false;
	}
	
	
	//disable default submit button and submit only when clicked (or entered when button has focus)
	function submitForm(formId,button)
	{
		var parentForm = document.getElementById(formId);
		if(parentForm!=null)
		{
			if(button!=null) button.disabled = true;
			parentForm.submit();					
		}
		return false;
	}
	
	
	//upload hrm file to database
	function submitProfileImage(formId,target,userid)
	{
		document.body.style.cursor = 'wait';
		var parentForm = document.getElementById(formId);
		if(parentForm!=null)
		{
			parentForm.target = target;
			parentForm.submit();					
			var t=setTimeout("updateImage("+userid+");",3000);
			var t=setTimeout("updateImage("+userid+");",6000);
			var t=setTimeout("updateImage("+userid+");",10000);
			var t=setTimeout("updateImage("+userid+");",20000);
		}
		return false;
	}

	function updateImage(userid)
	{
		var img = document.getElementById("pimage");
		img.src = "image?action=getprofile&u=" + userid + "&time=" + (new Date()).getTime();
		document.body.style.cursor = 'default';
	}
	
	
	function createXHRObject()
	{
		try { return new XMLHttpRequest(); } catch(e) {}
		try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
		try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
		alert(strYourBrowserDoesNotSupportXHR);
		return null;
	}
	function createAjaxRequest(request, responseHandler)
	{
		var xhr=null;
		try { xhr = new XMLHttpRequest(); } catch(e) {try { xhr = ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}}}
		
		if(xhr!=null)
		{
			try
			{
				request = request + "&tms=" + new Date().getTime();
				xhr.open("GET", request, true);
				xhr.setRequestHeader("Content-Type", "text/html;charset=UTF-8" );
				xhr.setRequestHeader("Accept-Charset","UTF-8");
				xhr.onreadystatechange = responseHandler;
				xhr.send(null);
			}catch(error){alert(strXHRError);}
		}
		else{alert(strYourBrowserDoesNotSupportXHR);}
		return xhr;
	}
	function createXmlAjaxRequest(url, params, responseHandler)
	{
		var xhr=null;
		try { xhr = new XMLHttpRequest(); } catch(e) {try { xhr = ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}}}

		if(xhr!=null)
		{
			try
			{
				xhr.open("POST", url, true);
				xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				//xhr.setRequestHeader("Accept-Charset","UTF-8");
				xhr.setRequestHeader("Content-length", params.length);
				xhr.onreadystatechange = responseHandler;
				//alert(params);
				xhr.send(params);
			}catch(error){alert(strXHRError);}
		}
		else{alert(strYourBrowserDoesNotSupportXHR);}
		return xhr;
	}
	/********** UTILITIES **********/

	
	

	
	
	
	
	
	
	
	/**
	 * This is a JavaScript library that will allow you to easily add some basic
	 * DHTML drop-down datepicker functionality to your Notes forms. This script
	 * is not as full-featured as others you may find on the Internet, but it's
	 * free, it's easy to understand, and it's easy to change.
	 * 
	 * You'll also want to include a stylesheet that makes the datepicker
	 * elements look nice. An example one can be found in the database that this
	 * script was originally released with, at:
	 * 
	 * http://www.nsftools.com/tips/NotesTips.htm#datepicker
	 * 
	 * I've tested this lightly with Internet Explorer 6 and Mozilla Firefox. I
	 * have no idea how compatible it is with other browsers.
	 * 
	 * version 1.5 December 4, 2005 Julian Robichaux -- http://www.nsftools.com
	 * 
	 * HISTORY -- version 1.0 (Sept. 4, 2004): Initial release.
	 *  -- version 1.1 (Sept. 5, 2004): Added capability to define the date
	 * format to be used, either globally (using the defaultDateSeparator and
	 * defaultDateFormat variables) or when the displayDatePicker function is
	 * called.
	 *  -- version 1.2 (Sept. 7, 2004): Fixed problem where datepicker x-y
	 * coordinates weren't right inside of a table. Fixed problem where
	 * datepicker wouldn't display over selection lists on a page. Added a call
	 * to the datePickerClosed function (if one exists) after the datepicker is
	 * closed, to allow the developer to add their own custom validation after a
	 * date has been chosen. For this to work, you must have a function called
	 * datePickerClosed somewhere on the page, that accepts a field object as a
	 * parameter. See the example in the comments of the updateDateField
	 * function for more details.
	 *  -- version 1.3 (Sept. 9, 2004) Fixed problem where adding the <div> and
	 * <iFrame> used for displaying the datepicker was causing problems on IE 6
	 * with global variables that had handles to objects on the page (I fixed
	 * the problem by adding the elements using document.createElement() and
	 * document.body.appendChild() instead of document.body.innerHTML += ...).
	 *  -- version 1.4 (Dec. 20, 2004) Added "targetDateField.focus();" to the
	 * updateDateField function (as suggested by Alan Lepofsky) to avoid a
	 * situation where the cursor focus is at the top of the form after a date
	 * has been picked. Added "padding: 0px;" to the dpButton CSS style, to keep
	 * the table from being so wide when displayed in Firefox.
	 *  -- version 1.5 (Dec 4, 2005) Added display=none when datepicker is
	 * hidden, to fix problem where cursor is not visible on input fields that
	 * are beneath the date picker. Added additional null date handling for date
	 * errors in Safari when the date is empty. Added additional error handling
	 * for iFrame creation, to avoid reported errors in Opera. Added onMouseOver
	 * event for day cells, to allow color changes when the mouse hovers over a
	 * cell (to make it easier to determine what cell you're over). Added
	 * comments in the style sheet, to make it more clear what the different
	 * style elements are for.
	 */

	var datePickerDivID = "datepicker";
	var iFrameDivID = "datepickeriframe";

	// these variables define the date formatting we're expecting and
	// outputting.
	// If you want to use a different format by default, change the
	// defaultDateSeparator
	// and defaultDateFormat variables either here or on your HTML page.
	var defaultDateSeparator = "/";        // common values would be "/" or "."
	var defaultDateFormat = "mdy";    // valid values are "mdy", "dmy", and
										// "ymd"
	var dateSeparator = defaultDateSeparator;
	var dateFormat = defaultDateFormat;

	var strLink = "";
	/**
	 * This is the main function you'll call from the onClick event of a button.
	 * Normally, you'll have something like this on your HTML page:
	 * 
	 * Start Date: <input name="StartDate"> <input type=button value="select"
	 * onclick="displayDatePicker('StartDate');">
	 * 
	 * That will cause the datepicker to be displayed beneath the StartDate
	 * field and any date that is chosen will update the value of that field. If
	 * you'd rather have the datepicker display beneath the button that was
	 * clicked, you can code the button like this:
	 * 
	 * <input type=button value="select" onclick="displayDatePicker('StartDate',
	 * this);">
	 * 
	 * So, pretty much, the first argument (dateFieldName) is a string
	 * representing the name of the field that will be modified if the user
	 * picks a date, and the second argument (displayBelowThisObject) is
	 * optional and represents an actual node on the HTML document that the
	 * datepicker should be displayed below.
	 * 
	 * In version 1.1 of this code, the dtFormat and dtSep variables were added,
	 * allowing you to use a specific date format or date separator for a given
	 * call to this function. Normally, you'll just want to set these defaults
	 * globally with the defaultDateSeparator and defaultDateFormat variables,
	 * but it doesn't hurt anything to add them as optional parameters here. An
	 * example of use is:
	 * 
	 * <input type=button value="select" onclick="displayDatePicker('StartDate',
	 * false, 'dmy', '.');">
	 * 
	 * This would display the datepicker beneath the StartDate field (because
	 * the displayBelowThisObject parameter was false), and update the StartDate
	 * field with the chosen value of the datepicker using a date format of
	 * dd.mm.yyyy
	 */
	function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep, link)
	{
	  var targetDateField = document.getElementsByName (dateFieldName).item(0);
	 
	  // if we weren't told what node to display the datepicker beneath, just
		// display it
	  // beneath the date field we're updating
	  if (!displayBelowThisObject)
	    displayBelowThisObject = targetDateField;
	 
	  // if a date separator character was given, update the dateSeparator
		// variable
	  if (dtSep)
	    dateSeparator = dtSep;
	  else
	    dateSeparator = defaultDateSeparator;
	 
	  // if a date format was given, update the dateFormat variable
	  if (dtFormat)
	    dateFormat = dtFormat;
	  else
	    dateFormat = defaultDateFormat;
	 
	  // deal with elements inside tables and such
	  var parent = displayBelowThisObject;
	  var bodyHeight = Math.max(document.body.offsetHeight, window.innerHeight);
	  var bodyWidth = document.body.offsetWidth;
	  var x = parent.offsetLeft;// + parent.width;
	  var y = parent.offsetTop + parent.offsetHeight;// + parent.height;
		
	  // deal with elements inside tables and such
	  var p = parent;
	  //if(p.offsetTop>0) y += p.offsetTop;
	  while (p.offsetParent) 
	  {
		  p = p.offsetParent;
		  if(p.offsetLeft>0) x += p.offsetLeft;
		  if(p.offsetTop>0) y += p.offsetTop;
	  }
	  if( (x+300)>document.body.offsetWidth){x-=300;}
	  if(y<0) y=50;

	  //link, added by TR 8.5.2009
	  if (link)
		  strLink = link;
	  
	  drawDatePicker(targetDateField, x, y);
	}


	/**
	Draw the datepicker object (which is just a table with calendar elements) at the
	specified x and y coordinates, using the targetDateField object as the input tag
	that will ultimately be populated with a date.

	This function will normally be called by the displayDatePicker function.
	*/
	function drawDatePicker(targetDateField, x, y)
	{
	  var dt = getFieldDate(targetDateField.value );
	 
	  // the datepicker table will be drawn inside of a <div> with an ID
		// defined by the
	  // global datePickerDivID variable. If such a div doesn't yet exist on
		// the HTML
	  // document we're working with, add one.
	  if (!document.getElementById(datePickerDivID)) 
	  {
	    // don't use innerHTML to update the body, because it can cause global variables
	    // that are currently pointing to objects on the page to have bad
		// references
	    // document.body.innerHTML += "<div id='" + datePickerDivID + "'
		// class='dpDiv'></div>";
	    var newNode = document.createElement("div");
	    newNode.setAttribute("id", datePickerDivID);
	    newNode.setAttribute("class", "dpDiv");
	    newNode.setAttribute("style", "visibility: hidden;");
	    document.body.appendChild(newNode);
	  }

	  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
	  var pickerDiv = document.getElementById(datePickerDivID);
	  pickerDiv.style.position = "absolute";
	  pickerDiv.style.left = x + "px";
	  pickerDiv.style.top = y + "px";
	  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
	  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
	  pickerDiv.style.zIndex = 10000;
	 
	  // draw the datepicker table
	  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
	}


	/**
	This is the function that actually draws the datepicker calendar.
	*/
	function refreshDatePicker(dateFieldName, year, month, day)
	{
	  // if no arguments are passed, use today's date; otherwise, month and year
	  // are required (if a day is passed, it will be highlighted later)
	  var thisDay = new Date();
	 
	  if ((month >= 0) && (year > 0)) 
	  {
	    thisDay = new Date(year, month, 1);
	  } else 
	  {
	    day = thisDay.getDate();
	    thisDay.setDate(1);
	  }
	 
	  // the calendar will be drawn as a table
	  // you can customize the table elements with a global CSS style sheet,
	  // or by hardcoding style and formatting elements below
	  var crlf = "\r\n";
	  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
	  var xTABLE = "</table>" + crlf;
	  var TR = "<tr class='dpTR'>";
	  var TR_title = "<tr class='dpTitleTR'>";
	  var TR_days = "<tr class='dpDayTR'>";
	  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
	  var xTR = "</tr>" + crlf;
	  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave
																															// this
																															// tag
																															// open,
																															// because
																															// we'll
																															// be
																															// adding
																															// an
																															// onClick
																															// event
	  var TD_title = "<td colspan=2 class='dpTitleTD'>";
	  var TD_yeartitle = "<td colspan=3 class='dpTitleTD'>";
	  var TD_buttons = "<td class='dpButtonTD'>";
	  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
	  var TD_days = "<td class='dpDayTD'>";
	  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave
																																							// this
																																							// tag
																																							// open,
																																							// because
																																							// we'll
																																							// be
																																							// adding
																																							// an
																																							// onClick
																																							// event
	  var xTD = "</td>" + crlf;
	  var DIV_title = "<div class='dpTitleText'>";
	  var DIV_selected = "<div class='dpDayHighlight'>";
	  var xDIV = "</div>";
	 
	  // start generating the code for the calendar table
	  var html = TABLE;
	 
	  // this is the title bar, which displays the month and the buttons to
	  // go back to a previous month or forward to the next month
//	  html += TR_title;
//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -12, "&lt;&lt;") + xTD;
//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
//	  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 12, "&gt;&gt;") + xTD;
//	  html += xTR;
	  
	  html += TR_title;
	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
	  html += TD_title + monthArrayLong[ thisDay.getMonth()] + xTD;
	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;

//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -12, "&lt;") + xTD;
//	  html += TD_yeartitle + thisDay.getFullYear() + xTD;
//	  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 12, "&gt;") + xTD;
	  html += TD_yeartitle + getButtonCode(dateFieldName, thisDay, -12, "&lt;");
	  html += thisDay.getFullYear();
	  html += getButtonCode(dateFieldName, thisDay, 12, "&gt;") + xTD;
	  html += xTR;
	 
	  // this is the row that indicates which day of the week we're on
	  html += TR_days;
	  if(firstDayOfWeek==1)
	  {
		  for(i = 0; i < dayArrayShort.length; i++)
			  html += TD_days + dayArrayShort[i] + xTD;
	  }
	  else
	  {
		  html += TD_days + dayArrayShort[6] + xTD;
		  for(i = 0; i < dayArrayShort.length-1; i++)
			  html += TD_days + dayArrayShort[i] + xTD;
	  }
	  html += xTR;
	 
	  // now we'll start populating the table with days of the month
	  html += TR;
	 
	  // first, the leading blanks
	  if(firstDayOfWeek==1)
	  {
		  var d = thisDay.getDay();
		  if(d==0) d=7;
		  for (i = 1; i < d; i++)
			  html += TD + "&nbsp;" + xTD;
	  }
	  else
	  {
		  for (i = 0; i < thisDay.getDay(); i++)
			  html += TD + "&nbsp;" + xTD;
	  }
	 
	  // now, the days of the month
	  do 
	  {
	    dayNum = thisDay.getDate();
	    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
	    
	    if (dayNum == day)
	      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
	    else
	      html += TD + TD_onclick + dayNum + xTD;

	    // If first day is monday and this is Sunday, start a new row
	    if(firstDayOfWeek==1 && thisDay.getDay() == 0)
	        html += xTR + TR;
	    // If first day is sunday and this is a Saturday, start a new row
	    else if (firstDayOfWeek==7 && thisDay.getDay()==6)
	    	html += xTR + TR;
	    
	    // increment the day
	    thisDay.setDate(thisDay.getDate() + 1);
	  } while (thisDay.getDate() > 1)
	 
	  // fill in any trailing blanks
	  if(firstDayOfWeek==1)
	  {
		  var d = thisDay.getDay();
		  if(d==0) d=7;
		  if (d > 0) 
		  {
			  for (i = d; i<=7; i++)
				  html += TD + "&nbsp;" + xTD;
		  }
	  }
	  else if(firstDayOfWeek==7)
	  {
		  if (thisDay.getDay() > 0) 
		  {
		    for (i = 6; i > thisDay.getDay(); i--)
		    	html += TD + "&nbsp;" + xTD;
		  }
	  }
	  html += xTR;
	 
	  // add a button to allow the user to easily return to today, or close
		// the calendar
	  var today = new Date();
	  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
	  html += TR_todaybutton + TD_todaybutton;
	  html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>" + strThisMonth + "</button> ";
	  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>" + strClose + "</button>";
	  html += xTD + xTR;
	 
	  // and finally, close the table
	  html += xTABLE;
	 
	  document.getElementById(datePickerDivID).innerHTML = html;
	  // add an "iFrame shim" to allow the datepicker to display above
		// selection lists
	  adjustiFrame();
	}


	/**
	Convenience function for writing the code for the buttons that bring us back or forward
	a month.
	*/
	function getButtonCode(dateFieldName, dateVal, adjust, label)
	{
	  var newMonth = (dateVal.getMonth () + adjust) % 12;
	  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
	  if (newMonth < 0) 
	  {
	    newMonth += 12;
	    newYear += -1;
	  }
	 
	  return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
	}


	/**
	Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
	variables at the beginning of this script library.
	*/
	function getDateString(dateVal)
	{
	  var dayString = "00" + dateVal.getDate();
	  var monthString = "00" + (dateVal.getMonth()+1);
	  dayString = dayString.substring(dayString.length - 2);
	  monthString = monthString.substring(monthString.length - 2);
	 
	  switch (dateFormat) 
	  {
	    case "dmy" :
	      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
	    case "ymd" :
	      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
	    case "mdy" :
	    default :
	      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
	  }
	}


	/**
	Convert a string to a JavaScript Date object.
	*/
	function getFieldDate(dateString)
	{
	  var dateVal;
	  var dArray;
	  var d, m, y;
	 
	  try {
	    dArray = splitDateString(dateString);
	    if (dArray) {
	      switch (dateFormat) {
	        case "dmy" :
	          d = parseInt(dArray[0], 10);
	          m = parseInt(dArray[1], 10) - 1;
	          y = parseInt(dArray[2], 10);
	          break;
	        case "ymd" :
	          d = parseInt(dArray[2], 10);
	          m = parseInt(dArray[1], 10) - 1;
	          y = parseInt(dArray[0], 10);
	          break;
	        case "mdy" :
	        default :
	          d = parseInt(dArray[1], 10);
	          m = parseInt(dArray[0], 10) - 1;
	          y = parseInt(dArray[2], 10);
	          break;
	      }
	      dateVal = new Date(y, m, d);
	    } else if (dateString) {
	      dateVal = new Date(dateString);
	    } else {
	      dateVal = new Date();
	    }
	  } catch(e) {
	    dateVal = new Date();
	  }
	 
	  return dateVal;
	}


	/**
	Try to split a date string into an array of elements, using common date separators.
	If the date is split, an array is returned; otherwise, we just return false.
	*/
	function splitDateString(dateString)
	{
	  var dArray;
	  if (dateString.indexOf("/") >= 0)
	    dArray = dateString.split("/");
	  else if (dateString.indexOf(".") >= 0)
	    dArray = dateString.split(".");
	  else if (dateString.indexOf("-") >= 0)
	    dArray = dateString.split("-");
	  else if (dateString.indexOf("\\") >= 0)
	    dArray = dateString.split("\\");
	  else
	    dArray = false;
	 
	  return dArray;
	}

	/**
	Update the field with the given dateFieldName with the dateString that has been passed,
	and hide the datepicker. If no dateString is passed, just close the datepicker without
	changing the field value.

	Also, if the page developer has defined a function called datePickerClosed anywhere on
	the page or in an imported library, we will attempt to run that function with the updated
	field as a parameter. This can be used for such things as date validation, setting default
	values for related fields, etc. For example, you might have a function like this to validate
	a start date field:
	*/
	function datePickerClosed(dateField)
	{
	  var dateObj = getFieldDate(dateField.value);
	  var today = new Date();
	  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
	 
	  if (dateField.name == "StartDate") {
	    if (dateObj < today) {
	      // if the date is before today, alert the user and display the datepicker again
	      alert("Please enter a date that is today or later");
	      dateField.value = "";
	      document.getElementById(datePickerDivID).style.visibility = "visible";
	      adjustiFrame();
	    } else {
	      // if the date is okay, set the EndDate field to 7 days after the StartDate
	      dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
	      var endDateField = document.getElementsByName ("EndDate").item(0);
	      endDateField.value = getDateString(dateObj);
	    }
	  }
	}

	/**/
	function updateDateField(dateFieldName, dateString)
	{
	  var targetDateField = document.getElementsByName (dateFieldName).item(0);
	  if (dateString)
	  {
		if(strLink)
			window.location = strLink + dateString;
		else
			targetDateField.value = dateString;
	  }
	  var pickerDiv = document.getElementById(datePickerDivID);
	  pickerDiv.style.visibility = "hidden";
	  pickerDiv.style.display = "none";
	 
	  adjustiFrame();
	  targetDateField.focus();
	  targetDateField.onchange();
	  
	  // after the datepicker has closed, optionally run a user-defined
		// function called
	  // datePickerClosed, passing the field that was just updated as a
		// parameter
	  // (note that this will only run if the user actually selected a date
		// from the datepicker)
	  if ((dateString) && (typeof(datePickerClosed) == "function"))
	    datePickerClosed(targetDateField);
	}


	/**
	Use an "iFrame shim" to deal with problems where the datepicker shows up behind
	selection list elements, if they're below the datepicker. The problem and solution are
	described at:

	http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
	http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
	*/
	function adjustiFrame(pickerDiv, iFrameDiv)
	{
	  // we know that Opera doesn't like something about this, so if we
	  // think we're using Opera, don't even try
	  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
	  if (is_opera)
	    return;
	  
	  // put a try/catch block around the whole thing, just in case
	  try {
	    if (!document.getElementById(iFrameDivID)) {
	      // don't use innerHTML to update the body, because it can cause global variables
	      // that are currently pointing to objects on the page to have bad
			// references
	      // document.body.innerHTML += "<iframe id='" + iFrameDivID + "'
			// src='javascript:false;' scrolling='no' frameborder='0'>";
	      var newNode = document.createElement("iFrame");
	      newNode.setAttribute("id", iFrameDivID);
	      newNode.setAttribute("src", "javascript:false;");
	      newNode.setAttribute("scrolling", "no");
	      newNode.setAttribute ("frameborder", "0");
	      document.body.appendChild(newNode);
	    }
	    
	    if (!pickerDiv)
	      pickerDiv = document.getElementById(datePickerDivID);
	    if (!iFrameDiv)
	      iFrameDiv = document.getElementById(iFrameDivID);
	    
	    try {
	      iFrameDiv.style.position = "absolute";
	      iFrameDiv.style.width = pickerDiv.offsetWidth;
	      iFrameDiv.style.height = pickerDiv.offsetHeight ;
	      iFrameDiv.style.top = pickerDiv.style.top;
	      iFrameDiv.style.left = pickerDiv.style.left;
	      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
	      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
	      iFrameDiv.style.display = pickerDiv.style.display;
	    } catch(e) {
	    }
	 
	  } catch (ee) {
	  }
	 
	}
	
	
	
	
	/*
	 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
	 * in FIPS PUB 180-1
	 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
	 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
	 * Distributed under the BSD License
	 * See http://pajhome.org.uk/crypt/md5 for details.
	 */

	/*
	 * Configurable variables. You may need to tweak these to be compatible with
	 * the server-side, but the defaults work in most cases.
	 */
	var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase */
	var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance */
	var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode */

	/*
	 * These are the functions you'll usually want to call They take string
	 * arguments and return either hex or base-64 encoded strings
	 */
	function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
	function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
	function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
	function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
	function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
	function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

	/*
	 * Perform a simple self-test to see if the VM is working
	 */
	function sha1_vm_test()
	{
	  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
	}

	/*
	 * Calculate the SHA-1 of an array of big-endian words, and a bit length
	 */
	function core_sha1(x, len)
	{
	  /* append padding */
	  x[len >> 5] |= 0x80 << (24 - len % 32);
	  x[((len + 64 >> 9) << 4) + 15] = len;

	  var w = Array(80);
	  var a =  1732584193;
	  var b = -271733879;
	  var c = -1732584194;
	  var d =  271733878;
	  var e = -1009589776;

	  for(var i = 0; i < x.length; i += 16)
	  {
	    var olda = a;
	    var oldb = b;
	    var oldc = c;
	    var oldd = d;
	    var olde = e;

	    for(var j = 0; j < 80; j++)
	    {
	      if(j < 16) w[j] = x[i + j];
	      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
	      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
	                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
	      e = d;
	      d = c;
	      c = rol(b, 30);
	      b = a;
	      a = t;
	    }

	    a = safe_add(a, olda);
	    b = safe_add(b, oldb);
	    c = safe_add(c, oldc);
	    d = safe_add(d, oldd);
	    e = safe_add(e, olde);
	  }
	  return Array(a, b, c, d, e);

	}

	/*
	 * Perform the appropriate triplet combination function for the current
	 * iteration
	 */
	function sha1_ft(t, b, c, d)
	{
	  if(t < 20) return (b & c) | ((~b) & d);
	  if(t < 40) return b ^ c ^ d;
	  if(t < 60) return (b & c) | (b & d) | (c & d);
	  return b ^ c ^ d;
	}

	/*
	 * Determine the appropriate additive constant for the current iteration
	 */
	function sha1_kt(t)
	{
	  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
	         (t < 60) ? -1894007588 : -899497514;
	}

	/*
	 * Calculate the HMAC-SHA1 of a key and some data
	 */
	function core_hmac_sha1(key, data)
	{
	  var bkey = str2binb(key);
	  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

	  var ipad = Array(16), opad = Array(16);
	  for(var i = 0; i < 16; i++)
	  {
	    ipad[i] = bkey[i] ^ 0x36363636;
	    opad[i] = bkey[i] ^ 0x5C5C5C5C;
	  }

	  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
	  return core_sha1(opad.concat(hash), 512 + 160);
	}

	/*
	 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
	 * to work around bugs in some JS interpreters.
	 */
	function safe_add(x, y)
	{
	  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	  return (msw << 16) | (lsw & 0xFFFF);
	}

	/*
	 * Bitwise rotate a 32-bit number to the left.
	 */
	function rol(num, cnt)
	{
	  return (num << cnt) | (num >>> (32 - cnt));
	}

	/*
	 * Convert an 8-bit or 16-bit string to an array of big-endian words
	 * In 8-bit function, characters >255 have their hi-byte silently ignored.
	 */
	function str2binb(str)
	{
	  var bin = Array();
	  var mask = (1 << chrsz) - 1;
	  for(var i = 0; i < str.length * chrsz; i += chrsz)
	    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
	  return bin;
	}

	/*
	 * Convert an array of big-endian words to a string
	 */
	function binb2str(bin)
	{
	  var str = "";
	  var mask = (1 << chrsz) - 1;
	  for(var i = 0; i < bin.length * 32; i += chrsz)
	    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
	  return str;
	}

	/*
	 * Convert an array of big-endian words to a hex string.
	 */
	function binb2hex(binarray)
	{
	  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
	  var str = "";
	  for(var i = 0; i < binarray.length * 4; i++)
	  {
	    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
	           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
	  }
	  return str;
	}

	/*
	 * Convert an array of big-endian words to a base-64 string
	 */
	function binb2b64(binarray)
	{
	  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	  var str = "";
	  for(var i = 0; i < binarray.length * 4; i += 3)
	  {
	    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
	                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
	                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
	    for(var j = 0; j < 4; j++)
	    {
	      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
	      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
	    }
	  }
	  return str;
	}

	 
	 
	 /********** STATISTICS AJAX **********/
	 var divname;
	 var dwsdivname;
	 var topdivname;
	 var statxmlhttp;
	 var tltimer;
	 var statparams;
	 function getStatistics(dn1, dn2, dn3, p)
	 {
	 	divname = dn1;
	 	dwsdivname = dn2;
	 	topdivname = dn3;
	 	//alert(p);
	 	if(p!=null) statparams = p;
	 	else 
	 		statparams = "action=all&all=1&days=14&workouts=15&persons=15";
	 	refresh();
	 }
	 function refresh()
	 {
	 	var request = "toplist?" + statparams;
	 	statxmlhttp = createAjaxRequest(request, StatResponseHandler);
	 }

	 function StatResponseHandler()
	 {
	 	if (statxmlhttp==null) return;
	 	if (statxmlhttp.readyState==4)
	 	{
	 		var stat = statxmlhttp.responseXML.getElementsByTagName("statistics")[0];
	 		if(stat==null) return;
	 		
	 		// last workouts
	 		var fl = stat.getElementsByTagName("workoutlist");
	 		if(fl!=null)
	 		{
	 			var str = "";
	 			var htmlStr = "";

	 			var fb = statxmlhttp.responseXML.getElementsByTagName("workoutbean");
	 			for(var i=0; i<fb.length; i++)
	 			{
	 				var workout = fb[i];
	 				var id = workout.getAttribute("id");
	 				var uid = workout.getAttribute("uid");
	 				var name = workout.getAttribute("name");
	 				var username = workout.getAttribute("uname");
	 				var day = workout.getAttribute("d");
	 				var st = workout.getAttribute("st");

	 				htmlStr += day + " ";
	 				if(id>0) 
	 				{
	 					htmlStr += "<a target=\"_blank\" href=\"workout?id="+id+"&u="+uid+"\">" + name + "</a>";
	 				}
	 				else
	 				{
	 					htmlStr += name;
	 				}
	 				if(i<(fb.length-1)) htmlStr += "<br>";
	 			}

	 			if(htmlStr!=null && htmlStr!="")
	 			{
	 				//alert(htmlStr);
	 				var div = document.getElementById(divname);
	 				if(htmlStr.length>0)
	 				{
	 					//alert(statxmlhttp.responseText);
	 					div.innerHTML=htmlStr;
	 				}
	 				else
	 				{
	 					div.innerHTML="";
	 				}
	 			}
	 		}
	 		
	 		var dws = statxmlhttp.responseXML.getElementsByTagName("daysummary")[0];
	 		if(dws!=null)
	 		{
	 			var str = "";
	 			var htmlStr = "";
	 			var hours = dws.getAttribute("h");
	 			var minutes = dws.getAttribute("m")*1;
	 			var length = dws.getAttribute("l")*1.0;
	 			var calories = dws.getAttribute("c")*1.0;

	 			var m = minutes;
	 			if(minutes<10) m = "0" + minutes;
	 			htmlStr += hours + " h   " + m + " min / ";
	 			htmlStr += length.toFixed(2) + " km / -";
	 			htmlStr += calories + " kcal";
	 			htmlStr += " (-" + (calories/7000).toFixed(1) + " kg)";

	 			if(htmlStr!=null && htmlStr!="")
	 			{
	 				//alert(htmlStr);
	 				var div = document.getElementById(dwsdivname);
	 				if(htmlStr.length>0)
	 				{
	 					//alert(statxmlhttp.responseText);
	 					div.innerHTML=htmlStr;
	 				}
	 				else
	 				{
	 					div.innerHTML="";
	 				}
	 			}
	 		}
	 		
	 		// TOP 10
	 		var toplist = stat.getElementsByTagName("toplist");
	 		if(toplist!=null)
	 		{
	 			var str = "";
	 			var htmlStr = "";
 				var sortmode = toplist[0].getAttribute("s");
 				var mode = toplist[0].getAttribute("mode");
 				var bld = new Array(3);for(var i=0;i<3;i++)bld[i]=";font-size:12px;";
 				if(sortmode==null || sortmode<0)sortmode=0;
 				bld[sortmode]=";font-size:12px;font-weight:bold";

	 			var tu = statxmlhttp.responseXML.getElementsByTagName("topuser");
	 			for(var i=0; i<tu.length; i++)
	 			{
	 				var topuser = tu[i];
	 				var uid = topuser.getAttribute("u");
	 				var name = topuser.getAttribute("n");
	 				
	 				//training
	 				if(mode==0)
	 				{
		 				var duration = 1*topuser.getAttribute("d");//in milliseconds...
		 				//alert(topuser.getAttribute("dis")+" "+topuser.getAttribute("cal"));
		 				var distance = 1*topuser.getAttribute("dis");//kilometers...
		 				var calories = 1*topuser.getAttribute("cal");//kcal...
		 				var h = Math.floor(duration / 3600);	var m = ((duration % 3600) / 60).toFixed(0);
		 				if(m<10) m = "0" + m;
		 				htmlStr += "<div style=\"float:left;margin-bottom:5px;width:380px;\">";
		 				htmlStr += "<label style=\"float:left;width:20px;\">" + (i+1) + ".</label>" ;
		 				htmlStr += "<label style=\"float:left;width:100px;\">";
		 				if(uid>0) htmlStr += "<a target=\"_blank\" style=\"margin:0;\" href=\"frontpage?u=" + uid + "\">" + name + "</a>";
		 				else htmlStr += name;
		 				htmlStr += "</label>";
		 				htmlStr += "<label style=\"margin:0;float:left;width:80px;text-align:right" + bld[0] + "\">" + h + " h " + m + " min" + "</label>";
		 				htmlStr += "<label style=\"margin:0;float:left;width:70px;text-align:right" + bld[1] + "\">" + distance.toFixed(1) + " km</label>";
		 				htmlStr += "<label style=\"margin:0;float:left;width:85px;text-align:right" + bld[2] + "\">";
		 				if(calories>0) htmlStr+="-" + calories.toFixed(0) + " kcal";htmlStr+="</label>";
		 				htmlStr += "</div>";
	 				}
	 				//weight reduction
	 				else
	 				{
		 				var wr = 1*topuser.getAttribute("wr");//in milliseconds...
		 				var wrp = 1*topuser.getAttribute("wrp");//kcal...
		 				htmlStr += "<div style=\"float:left;margin-bottom:5px;width:380px;\">";
		 				htmlStr += "<label style=\"float:left;width:20px;\">" + (i+1) + ".</label>" ;
		 				htmlStr += "<label style=\"float:left;width:100px;\">";
		 				if(uid>0) htmlStr += "<a target=\"_blank\" style=\"margin:0;\" href=\"frontpage?u=" + uid + "\">" + name + "</a>";
		 				else htmlStr += name;
		 				htmlStr += "</label>";
		 				htmlStr += "<label style=\"margin:0;float:left;width:70px;text-align:right" + bld[0] + "\">" + wr.toFixed(1) + " kg</label>";
		 				htmlStr += "<label style=\"margin:0;float:left;width:70px;text-align:right" + bld[1] + "\">" + wrp.toFixed(1) + " %</label>";
		 				htmlStr += "</div>";
	 				}
	 			}

	 			if(htmlStr!=null && htmlStr!="")
	 			{
	 				var div = document.getElementById(topdivname);
	 				if(htmlStr.length>0)
	 				{
	 					//alert(statxmlhttp.responseText);
	 					div.innerHTML=htmlStr;
	 				}
	 				else
	 				{
	 					div.innerHTML="";
	 				}
	 			}
	 		}
	 		
	 		
	 		//refresh after 30s
	 		if(tltimer!=null) clearTimeout(tltimer);
	 		tltimer=setTimeout("refresh();",30000);
	 	}
	 }
	 /********** STATISTICS AJAX **********/

	 
	 
	 var foundFriendsDivName;
	 var friendsearchxmlhttp;
	 var friendaddxmlhttp;
	 /********** FRIENDS SEARCH AJAX **********/
	 function searchFriends(searchFieldName, searchResultsDivName)
	 {
		 //alert("searchFriends("+searchFieldName+", "+searchResultsDivName+")");
		 var friendSearchField = document.getElementById(searchFieldName);
		 foundFriendsDivName = searchResultsDivName;
		 

		 var word = friendSearchField.value;
		 if(word!=null)
		 {
			 if(word.length>0)
			 {
				word = word.replace(/%/ig, '_');
				word = word.replace(/&/ig, '_');
				word = word.replace(/-/ig, '_');
				//word = word.replace(/ /ig, '_____');
				word = word.replace(/[^a-zåäöèê0-9_ .,;'()=\/\\]/ig, '');

				var request = "friends?action=search&keyword=" + encodeURIComponent(word);
				friendsearchxmlhttp = createAjaxRequest(request, friendSearchResponseHandler);
			}
		}

	 }
	 function searchAllUsers(searchFieldName, searchResultsDivName)
	 {
		 //alert("searchFriends("+searchFieldName+", "+searchResultsDivName+")");
		 var friendSearchField = document.getElementById(searchFieldName);
		 foundFriendsDivName = searchResultsDivName;
		 
		 var request = "friends?action=search&keyword=allusers";
		 friendsearchxmlhttp = createAjaxRequest(request, friendSearchResponseHandler);
	 }

	 function friendSearchResponseHandler()
	 {
	 	if(friendsearchxmlhttp==null) return false;
	 	
	 	if (friendsearchxmlhttp.readyState==4 && friendsearchxmlhttp.status==200)
	 	{
		 	//alert("friendsearchxmlhttp.status="+friendsearchxmlhttp.status+"-friendsearchxmlhttp.readyState="+friendsearchxmlhttp.readyState);
	 		var fl = friendsearchxmlhttp.responseXML.getElementsByTagName("friendlist")[0];
	 		
	 		if(fl==null)
	 		{
	 			return false;
	 		}

	 		var htmlStr = "";
	 		var foundFriendsDiv = document.getElementById(foundFriendsDivName);
	 		foundFriendsDiv.style.display = "none";
	 		var fb = fl.getElementsByTagName("userbean");
	 		if(fb!=null)
	 		{
	 			if(fb.length>0)
	 			{
			 		htmlStr += "<table style=\"width:550px;border:0;display: block;\">";
			 		htmlStr += "<tr><th style=\"width:30px;\"></th><th style=\"width:150px;\">" + strName + "</th><th style=\"width:150px;\">" + strCity + "</th><th style=\"width:200px;\"></th><th></th></tr>";
		
			 		for(var i=0; i<fb.length; i++)
			 		{
			 			var user = fb[i];
			 			var id = user.getAttribute("id");
			 			var name = user.getAttribute("name");
			 			var city = user.getAttribute("city");
			 			htmlStr += "<tr><td><a href=\"frontpage?u=" + id + "\"><img style=\"vertical-align:middle;\" alt=\"\" src=\"image?action=getprofile&amp;u=" + id + "\" width=24 height=24></a></td>";
			 			htmlStr += "<td><a href=\"frontpage?u=" + id + "\">" + name + "</a></td>";
			 			htmlStr += "<td>" + city + "</td>";
			 			htmlStr += "<td><a href=\"\" onclick=\"requestFriend('" + id +  "','"+name+"');return false;\">" + strRequestToFriend + "</a></td></tr>";
			 		}
			 		htmlStr += "</table>";
	 			}
	 			else
	 			{
	 				htmlStr = strNoUsersFound;
	 			}
	 		}
 			else
 			{
 				htmlStr = strNoUsersFound;
 			}
	 		foundFriendsDiv.style.display = "block";
	 		foundFriendsDiv.innerHTML = htmlStr;

	 		return true;
	 	}
	 }
	 function requestFriend(userid, name)
	 {
         var question = strConfirmFriendRequest1 + " " + name + " " + strConfirmFriendRequest2;
		 var answer = confirm(question);
		 if (answer)
		 {
			 var request = "friends?action=request&u=" + encodeURIComponent(userid);
			 friendaddxmlhttp = createAjaxRequest(request, friendAddResponseHandler, friendaddxmlhttp);
		 }
	 }
	 function friendAddResponseHandler()
	 {
	 	if(friendaddxmlhttp==null) return;
	 	if (friendaddxmlhttp.readyState==4 && friendaddxmlhttp.status==200)
	 	{
	 		var friendrequested = friendaddxmlhttp.responseXML.getElementsByTagName("friendrequest")[0];
	 		if(friendrequested==null)
	 		{
	 			alert(" "+strFriendCouldNotBeRequested);
	 		}
	 		else
	 		{
		 		var fr = friendrequested.getElementsByTagName("friend");
		 		var user = fr[0];
	 			var name = user.getAttribute("name");

	 			if(name!=null && name!="")
	 			{
	 				//alert(" " + strFriendRequested + " " + name);
	 				showDialog(0,strFriendRequested,strFriendRequested + " " + name,"prompt",1,3,"OK","hideDialog()",null,null,null,null);
	 				//showDialog(null,"ok","yes","prompt",0,"OK","hideDialog()","","","","");
	 				return true;
	 			}
	 			else
	 			{
	 				alert(" " +strFriendCouldNotBeRequested);
	 			}
	 		}
	 	}
	 	return false;
	 }
	 /********** FRIENDS SEARCH AJAX **********/
	 
	 
	 /********** Show help *********/
	 var helptimer;
	 function showHelp(parent, text, timeout)
	 {
	 	var bodyHeight = Math.max(document.body.offsetHeight, window.innerHeight);
	 	var bodyWidth = document.body.offsetWidth;
	 	var x = parent.offsetLeft;// + parent.width;
	 	var y = parent.offsetTop + parent.offsetHeight;// + parent.height;

	 	// deal with elements inside tables and such
	 	var p = parent;
 	    //if(p.offsetTop>0) y += p.offsetTop;
	 	while (p.offsetParent) 
	 	{
	 		p = p.offsetParent;
	 	    if(p.offsetLeft>0) x += p.offsetLeft;
	 	    if(p.offsetTop>0) y += p.offsetTop;
	 	}
	 	if( (x+350)>document.body.offsetWidth){x-=350;}
	 	if(y<0) y=50;
	 	
	 	var dialogid = "helpdiv";
	 	var afdFrame = document.getElementById(dialogid);
	 	if (!afdFrame) 
	 	{
	 		afdFrame = document.createElement("div");
	 		afdFrame.setAttribute("id", dialogid);
	 		afdFrame.setAttribute("style", "visibility: hidden;background: url(\"http://www.trainit.fi/img/mask90p.png\") top repeat");
	 		afdFrame.style.opacity = 0.95;
	 		afdFrame.style.filter = 'alpha(opacity=95)';
	 		afdFrame.alpha = 95;

	 		document.body.appendChild(afdFrame);
	 	}
	 	//afdFrame.innerHTML = "<div style=\"width:400px;height:auto;color:#0000ff;background-color:#e0f0f0;padding:5px;border: 1px solid #000;\" >" +	text +	"</div>"; 
	 	afdFrame.innerHTML = "<div style=\"width:350px;height:auto;color:#0000ff;background-color:#ffffff;padding:5px;border: 1px solid #000;\" ><div>" +	text  +
	 	"</div><div style=\"margin-top:20px\"><a title=\"" + strClose + "\" href=\"javascript:hideHelp();\">" + strClose + "</a></div>" +	"</div>"; 
	 	//afdFrame.innerHTML = "<div style=\"width:400px;height:auto;color:#0000ff;background: url(\"http://www.trainit.fi/img/mask90p.png\") top repeat transparent;padding:5px;border: 1px solid #000;\" >" +	text +	"</div>";

		afdFrame.style.position = "absolute";
	 	afdFrame.style.left = x + "px";
	 	afdFrame.style.top = y + "px";
	 	afdFrame.style.visibility = "visible";//(afdFrame.style.visibility == "visible" ? "hidden" : "visible"); //"visible";
	 	afdFrame.style.display = "block";
	 	afdFrame.style.zIndex = 10000;
	 	afdFrame.style.width = "auto";
	 	afdFrame.style.height = "auto";
	 	if(helptimer!=null) clearTimeout(helptimer);
		if(timeout>0) helptimer=setTimeout("hideHelp();", timeout);
	 }
	 function hideHelp()
	 {
	 	if(helptimer!=null) clearTimeout(helptimer);
	 	var helpdiv = document.getElementById("helpdiv");
	 	if (helpdiv) 
	 	{
		 	helpdiv.style.visibility = "hidden";
	 	}	 
	 }
	 /********** Show help *********/
	 

	 /********** Show menu help *********/
	 function showMenuHelp(parent, text)
	 {
		if(text==null || text=="")return;
		if(text.length<5)return;
	 	var bodyHeight = Math.max(document.body.offsetHeight, window.innerHeight);
	 	var bodyWidth = document.body.offsetWidth;

	 	var obj = parent.getBoundingClientRect();
	 	var x=obj.left;
	 	var y=obj.bottom+5;
	 	
	 	var scr=0;
	 	if (document.body && document.body.scrollTop) scr=document.body.scrollTop;
	 	// IE5 or DTD 3.2
	 	else if (document.documentElement && !document.documentElement.scrollTop) scr=0;
	 	// IE6 +4.01 but no scrolling going on
	 	else if (document.documentElement && document.documentElement.scrollTop) scr=document.documentElement.scrollTop;
	 	// IE6 +4.01 and user has scrolled
	 	//alert(scr);
	 	y+=scr;
	 	
	 	var dialogid = "menuhelpdiv";
	 	var afdFrame = document.getElementById(dialogid);
	 	if (!afdFrame) 
	 	{
	 		afdFrame = document.createElement("div");
	 		afdFrame.setAttribute("id", dialogid);
	 		//afdFrame.setAttribute("style", "visibility: hidden;background: url(\"http://www.trainit.fi/img/mask90p.png\") top repeat");
	 		afdFrame.setAttribute("style", "visibility: hidden;background: none");
	 		afdFrame.style.opacity = 0.95;
	 		afdFrame.style.filter = 'alpha(opacity=95)';
	 		afdFrame.alpha = 95;

	 		document.body.appendChild(afdFrame);
	 		//var menudiv = document.getElementById('menudiv');
	 		//menudiv.appendChild(afdFrame);
	 	}
	 	//afdFrame.innerHTML = "<div style=\"width:400px;height:auto;color:#0000ff;background-color:#e0f0f0;padding:5px;border: 1px solid #000;\" >" +	text +	"</div>"; 
	 	afdFrame.innerHTML = "<div style=\"background:transparent;width:auto;height:auto;color:#0000ff;padding:0;border:0;\">"+text+"</div>";
	 	//<div style=\"margin-top:20px\"><a title=\"" + strClose + "\" href=\"javascript:hideHelp();\">" + strClose + "</a></div>" +	"</div>"; 
	 	//afdFrame.innerHTML = "<div style=\"width:400px;height:auto;color:#0000ff;background: url(\"http://www.trainit.fi/img/mask90p.png\") top repeat transparent;padding:5px;border: 1px solid #000;\" >" +	text +	"</div>";

		afdFrame.style.position = "absolute";
	 	afdFrame.style.left = x + "px";
	 	afdFrame.style.top = y + "px";
	 	afdFrame.style.visibility = "visible";//(afdFrame.style.visibility == "visible" ? "hidden" : "visible"); //"visible";
	 	afdFrame.style.display = "block";
	 	afdFrame.style.zIndex = 10000;
	 	afdFrame.style.width = "auto";
	 	afdFrame.style.height = "auto";
	 }
	 function hideMenuHelp()
	 {
	 	var helpdiv = document.getElementById("menuhelpdiv");
	 	if(helpdiv){helpdiv.style.visibility="hidden";}	 
	 }
	 /********** Show menu help *********/
	 
	 
	function openNewWindow(URLtoOpen, windowName, windowFeatures)
	{
		//alert("openNewWindow("+URLtoOpen+", "+windowName+", "+windowFeatures+")");
		//newWindow=window.open(URLtoOpen, windowName, windowFeatures);
		newWindow=window.open(URLtoOpen, windowName, windowFeatures);
		return newWindow;
	}
	 
	var xmlhttpfbshare;
	var shlnk;
	function shareToFb(e, uri, uid, type, linkid, link, name)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		
//		var strShareToFacebok
//		showDialog(e,strRepeatingWorkout + title,
//				'<p>' + strModifyAllRepeatingWorkouts + '</p>',
//				'prompt',1,
//				0,
//				"Facebook",
//				"goToUrl('"+linkall+"')",
//				"Net",
//				"goToUrl('"+link+"')",
//				null,
//				null);
//		
		var answer = confirm(strConfirmShareToFacebook);
		if (answer)
		{
			//first add 
			shlnk = "http://www.facebook.com/sharer.php?u=" + uri;
	
			//alert("shareToFb("+uri+", "+uid+", "+type+", "+linkid+", "+link+")");
			var request = "share?action=new&u="+encodeURIComponent(uid)+"&type="+encodeURIComponent(type)+
				"&linkid="+encodeURIComponent(linkid)+"&link="+encodeURIComponent(link)+"&name="+encodeURIComponent(name);
			xmlhttpfbshare = createAjaxRequest(request, FbShareResponseHandler);
			//Should be checked if succeeded...
		}
	}
	function FbShareResponseHandler()
	{
		if(xmlhttpfbshare==null) return;
		if (xmlhttpfbshare.readyState==4)
		{
			window.open(shlnk, 'Facebook', 'height=400,width=600,resizable=yes');
		}
	}
	
	var xmlhttpnetshare;
	var netsharelnk;
	function shareToNet(e, uri, uid, type, linkid, link, name)
	{
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
		
		var answer = confirm(strConfirmShareToNet);
		if (answer)
		{
			//first add 
			netsharelnk = "http://www.trainit.fi:8080/TrainIt/" + link;
	
			//alert("shareToFb("+uri+", "+uid+", "+type+", "+linkid+", "+link+")");
			var request = "share?action=new&u="+encodeURIComponent(uid)+"&type="+encodeURIComponent(type)+
				"&linkid="+encodeURIComponent(linkid)+"&link="+encodeURIComponent(link)+"&name="+encodeURIComponent(name);
			xmlhttpnetshare = createAjaxRequest(request, NetShareResponseHandler);
			//Should be checked if succeeded...
		}
	}
	function NetShareResponseHandler()
	{
		if(xmlhttpnetshare==null) return;
		if (xmlhttpnetshare.readyState==4)
		{
			showDialog(null,strNetSharing,
					'<p>' + strSharedToNet + ':</p><p><a href=\"' + netsharelnk + '\">' + netsharelnk + '</a></p><p>' + strCopySharedLink + '</p>',
					'prompt',1,
					0,
					strOK,
					"hideDialog()",
					null,
					null,
					null,
					null);
		}
	}

	
	
	
	
	
	
	
	
	
	
	// global variables //
	var TIMER = 5;
	var SPEED = 10;
	var WRAPPER = 'type1';

	// calculate the current window width //
	function pageWidth() {
	  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
	}

	// calculate the current window height //
	function pageHeight() {
	  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
	}

	// calculate the current window vertical offset //
	function topPosition() {
	  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
	}

	// calculate the position starting at the left of the window //
	function leftPosition() {
	  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
	}

	// build/show the dialog box, populate the data and call the fadeDialog function //
	function showDialog(e,title,message,type,modal,autohide,btn1,action1,btn2,action2,btn3,action3) 
	{
//		alert("showDialog("+e+","+title+","+message+","+type+","+modal+","+autohide+","+btn1+","+action1+","+btn2+","+action2+","+btn3+","+action3+")");

		//stop bubbling to lower components
		if(e!=null)
		{
			//e = window.event;
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
		}
		
		if(!type)
		{
			type = 'error';
		}
		var dialog;
		var dialogheader;
		var dialogclose;
		var dialogtitle;
		var dialogcontent;
		var dialogtext;
		var dialogbuttons;
		var dialogmask;
	  
		if(!document.getElementById('dialog'))
		{
			dialog = document.createElement('div');
			dialog.id = 'dialog';
			dialogheader = document.createElement('div');
			dialogheader.id = 'dialog-header';
			dialogtitle = document.createElement('div');
			dialogtitle.id = 'dialog-title';
			dialogclose = document.createElement('div');
			dialogclose.id = 'dialog-close';
			dialogcontent = document.createElement('div');
			dialogcontent.id = 'dialog-content';
			dialogtext = document.createElement('div');
			dialogtext.id = 'dialog-text';
			dialogbuttons = document.createElement('div');
			dialogbuttons.id = 'dialog-buttons';
			if(modal>0)
			{
				dialogmask = document.createElement('div');
				dialogmask.id = 'dialog-mask';
				document.body.appendChild(dialogmask);
			}
			document.body.appendChild(dialog);
			dialog.appendChild(dialogheader);
			dialogheader.appendChild(dialogtitle);
			dialogheader.appendChild(dialogclose);
			dialog.appendChild(dialogcontent);
			dialogcontent.appendChild(dialogtext);
			dialogcontent.appendChild(dialogbuttons);
			dialogclose.setAttribute('onclick','hideDialog()');
			dialogclose.onclick = hideDialog;
			
			if(btn1!=null) dialogbuttons.appendChild(createButton(btn1,action1));
			if(btn2!=null) dialogbuttons.appendChild(createButton(btn2,action2));
			if(btn3!=null) dialogbuttons.appendChild(createButton(btn3,action3));
		} 
		else
		{
			dialog = document.getElementById('dialog');
			dialogheader = document.getElementById('dialog-header');
			dialogtitle = document.getElementById('dialog-title');
			dialogclose = document.getElementById('dialog-close');
			dialogcontent = document.getElementById('dialog-content');
			dialogtext = document.getElementById('dialog-text');
			dialogbuttons = document.getElementById('dialog-buttons');
			if(modal>0)
			{
				dialogmask = document.getElementById('dialog-mask');
				dialogmask.style.visibility = "visible";
			}
			dialog.style.visibility = "visible";
		}
//		dialog.style.opacity = 1.00;
//		dialog.style.filter = 'alpha(opacity=100)';
//		dialog.alpha = 100;
		dialog.style.opacity = 0.00;
		dialog.style.filter = 'alpha(opacity=0)';
		dialog.alpha = 0;
		var width = pageWidth();//900;//
		var height = pageHeight();
		var left = 0;//leftPosition();
		var top = topPosition();
		var dialogwidth = dialog.offsetWidth;
		var dialogheight = dialog.offsetHeight;
		var topposition = top + (height / 3) - (dialogheight / 2);
		var leftposition = left + (width / 2) - (dialogwidth / 2);
		dialog.style.top = topposition + "px";
		dialog.style.left = leftposition + "px";
		dialogheader.className = type + "header";
		dialogtitle.innerHTML = title;
		dialogcontent.className = type;
		dialogtext.className = "dialog-text";
		dialogbuttons.className = "dialog-buttons";
		dialogtext.innerHTML = message;
		//var content = document.getElementById("type1");
		//if(content==null) content = document.getElementById("type2");
		//if(content==null) content = document.getElementById("type4");
		if(modal>0)
		{
			dialogmask.style.height = (document.body.offsetHeight + 200) + 'px';
		}
		dialogclose.style.visibility = "visible";

		dialog.timer = setInterval("fadeDialog(1)", TIMER);
		if(autohide)
		{
			dialogclose.style.visibility = "hidden";
			window.setTimeout("hideDialog()", (autohide * 1000));
		}
		else
		{
			dialogclose.style.visibility = "visible";
		}
	}

	// hide the dialog box //
	function hideDialog()
	{
		var dialog = document.getElementById('dialog');
		dialog.style.visibility = "hidden";

		var mask = document.getElementById('dialog-mask');
		if(mask!=null) mask.style.visibility = "hidden";

		dialog = null;
//		clearInterval(dialog.timer);
//		dialog.timer = setInterval("fadeDialog(0)", TIMER);
	}

	// fade-in the dialog box //
	function fadeDialog(flag)
	{
		if(flag == null)
		{
			flag = 1;
		}
		var dialog = document.getElementById('dialog');
		var value;
		if(flag == 1)
		{
			value = dialog.alpha + SPEED;
		}
		else
		{
			value = dialog.alpha - SPEED;
		}
		dialog.alpha = value;
		dialog.style.opacity = (value / 100);
		dialog.style.filter = 'alpha(opacity=' + value + ')';
		if(value >= 99)
		{
			clearInterval(dialog.timer);
			dialog.timer = null;
		}
		else if(value <= 1)
		{
			dialog.style.visibility = "hidden";
			document.getElementById('dialog-mask').style.visibility = "hidden";
			clearInterval(dialog.timer);
		}
	}
	
	
	/*frontpage bmi and ortho hr calculations*/
	function showBmi(height, wname, bminame)
	{
		var wf = document.getElementById(wname);var bmif = document.getElementById(bminame);
		if(wf==null || bmif==null) return;
		var h = height / 100.0;var w = wf.value*1.0;
		if(h>0 && w>0){var bmi = w / (h*h);bmif.innerHTML = "BMI="+bmi.toFixed(1);}
		else bmif.innerHTML="";
	}
	function showOrthoHr(rhrname,shrname,orthoname)
	{
		var rhrf = document.getElementById(rhrname);var shrf = document.getElementById(shrname);var ohrf = document.getElementById(orthoname);
		if(rhrf!=null && shrf!=null && ohrf!=null)
		{
			var rhr = rhrf.value;var shr = shrf.value;
			if(rhr>0 && shr>0){var orto = shr-rhr;if(orto>20) ohrf.innerHTML = "HR<i style=\"font-size: x-small;vertical-align: sub\">o</i>=<b style=\"color:red\">" + orto.toFixed(0) + "</b>";else ohrf.innerHTML = "HR<i style=\"font-size: x-small;vertical-align: sub\">o</i>=" + orto.toFixed(0);}
			else ohrf.innerHTML="";
		}
	}
	
	
	function checkAndSaveWorkout()
	{
		
	}
	function checkAndSaveEating()
	{
		
	}
	function checkAndSaveEating()
	{
	}

	function checkInt(intf, limit)
	{
		var isok=true;
		var ifv=intf.value;
		try
		{
			if(parseInt(ifv)!=ifv) isok=false;
		}catch(e){isok=false;}
		if(limit>0)if(ifv>limit)isok=false;
		setError(isok, intf);
	}
	function checkFloat(ff, limit)
	{
		var isok=true;
		var ffv=ff.value.replace(/,/ig, '.');
		try
		{
			if(parseFloat(ffv).toString()!=ffv) isok=false;
		}catch(e){isok=false;}
		if(limit>0)if(ffv>limit)isok=false;
		setError(isok, ff);
	}
	function checkDate(df)
	{
		var isok=true;
		var dfv=df.value;
		if(dfv.length!=10) isok=false;
		else
		{
			if(dfv.charAt(4)!='-') isok=false;
			if(dfv.charAt(7)!='-') isok=false;
		}
		setError(isok, df);
	}
	function checkTime(tf)
	{
		var isok=true;
		try
		{
			var tfv=tf.value;
			if(tfv.length==1 || tfv.length==2)
			{
				var h=parseInt(tfv);
				if(isNaN(h)) isok=false;
				else if(h<0 || h>24) isok=false;
			}
			else if(tfv.length==4 || tfv.length==5)
			{
				var b=tfv.length-4;
				if(tfv.charAt(b+1)!=':') isok=false;
				else
				{
					var h=parseInt(tfv.substring(b+0,b+1)), m=parseInt(tfv.substring(b+2,b+4));
					if(isNaN(h) || isNaN(m)) isok=false;
					else if(h<0 || h>24 || m<0 || m>59) isok=false;
				}
			}
			else if(tfv.length==7 || tfv.length==8)
			{
				var b=tfv.length-7;
				if(tfv.charAt(b+1)!=':' || tfv.charAt(b+4)!=':') isok=false;
				else
				{
					var h=parseInt(tfv.substring(b+0,b+1)), m=parseInt(tfv.substring(b+2,b+4)), s=parseInt(tfv.substring(b+5,b+7));
					if(isNaN(h) || isNaN(m) || isNaN(s)) isok=false;
					else if(h<0 || h>24 || m<0 || m>59 || s<0 || s>59) isok=false;
				}
			}
			else isok=false;
		}catch(e){isok=false;}
		
		setError(isok, tf);
	}
	function setError(isok, field)
	{
		if(!isok){field.style.color="#ff0000";field.style.textDecoration="line-through";}
		else{field.style.color="#000000";field.style.textDecoration="none";}
	}
	
	function checkRepeatTime(sdfn, edfn)
	{
		var sdf=document.getElementById(sdfn);
		var edf=document.getElementById(edfn);
		try
		{
			var sdfv=sdf.value,edfv=edf.value;
			var startDate=new Date(),endDate=new Date();
			startDate.setFullYear(sdfv.substring(0,4), sdfv.substring(5,7)-1, sdfv.substring(8,10));
			endDate.setFullYear(edfv.substring(0,4), edfv.substring(5,7)-1, edfv.substring(8,10));
			var one_day=1000*60*60*24;
			var diff = (endDate.getTime()-startDate.getTime()) / one_day;
			if(diff>3*31)
			{
				endDate.setTime(startDate.getTime() + 93*one_day);
				edf.value=endDate.getFullYear()+"-"+addLeadingZero(endDate.getMonth()+1,2)+"-"+addLeadingZero(endDate.getDate(),2);
			}
			else if(diff<0)
			{
				endDate.setTime(startDate.getTime());
				edf.value=endDate.getFullYear()+"-"+addLeadingZero(endDate.getMonth()+1,2)+"-"+addLeadingZero(endDate.getDate(),2);
			}
			setError(true, edf);
		}catch(e){setError(false,edf);}	
	}
	
	function checkStartAndEndDate(sdfn, edfn)
	{
		var sdf=document.getElementById(sdfn);
		var edf=document.getElementById(edfn);
		try
		{
			checkDate(sdf);checkDate(edf);
			var sdfv=sdf.value,edfv=edf.value;
			var startDate=new Date(),endDate=new Date();
			startDate.setFullYear(sdfv.substring(0,4), sdfv.substring(5,7)-1, sdfv.substring(8,10));
			endDate.setFullYear(edfv.substring(0,4), edfv.substring(5,7)-1, edfv.substring(8,10));
			var one_day=1000*60*60*24;
			var diff = (endDate.getTime()-startDate.getTime()) / one_day;
			if(diff<0)
			{
				endDate.setTime(startDate.getTime());
				edf.value=endDate.getFullYear()+"-"+addLeadingZero(endDate.getMonth()+1,2)+"-"+addLeadingZero(endDate.getDate(),2);
			}
			setError(true, edf);
		}catch(e){setError(false,edf);}	
	}
	function addLeadingZero(num,count)
	{
		var numZeropad = num + '';
		while(numZeropad.length < count){numZeropad = "0" + numZeropad;}
		return numZeropad;
	}
	
	
	var xmlhttpeps,msdivname,tsdivname,selectdivname;
	function updateEventParticipation(msdn,tsdn,seldn,request)
	{
		msdivname=msdn;tsdivname=tsdn;selectdivname=seldn;
		if(xmlhttpeps!=null){xmlhttpeps.abort();xmlhttpeps=null;}
		xmlhttpeps = createAjaxRequest(request, EventParticipateResponseHandler);
	}
	var statesandnames;
	function updateEventParticipationAndNames(snd,request)
	{
		statesandnames=snd;
		if(xmlhttpeps!=null){xmlhttpeps.abort();xmlhttpeps=null;}
		xmlhttpeps = createAjaxRequest(request, EventParticipateResponseHandler);
	}
	function EventParticipateResponseHandler()
	{
		if(xmlhttpeps==null) return;
		if (xmlhttpeps.readyState==4)
		{
			var s = xmlhttpeps.responseXML.getElementsByTagName("epstate");
			var stat = null;if(s!=null) stat = s[0];
			if(stat!=null)
			{
				var mystate = stat.getAttribute("mystate");
				var reject = stat.getAttribute("reject");
				var accept = stat.getAttribute("accept");
				var maybe = stat.getAttribute("maybe");
				
				//update states
				var msd = document.getElementById(msdivname);
				var tsd = document.getElementById(tsdivname);
				var sdiv = document.getElementById(selectdivname);
				sdiv.style.display="none";
				if(mystate==1) msd.innerHTML = "<i style=\"color:#ff0000;\">" + strMrRejected + "</i>";
				else if(mystate==2) msd.innerHTML = "<i style=\"color:#008000;\">" + strMrAccepted + "</i>";
				else if(mystate==3) msd.innerHTML = "<i style=\"color:#0000ff;\">" + strMrMaybe + "</i>";
				
				tsd.innerHTML = "";
				if(accept>0) tsd.innerHTML += "<label style=\"width:auto;color:#008000;\">" + accept+" "+strAccepted+"</label><br>";
				if(maybe>0) tsd.innerHTML += "<label style=\"width:auto;color:#0000ff;\">" + maybe+" "+strMaybe+"</label><br>";
				if(reject>0) tsd.innerHTML += "<label style=\"width:auto;color:#ff0000;\">" + reject+" "+strRejected+"</label><br>";
			}
			var statesAndNames = xmlhttpeps.responseXML.getElementsByTagName("epstatenames")[0];
			if(statesAndNames!=null)
			{
				var content = statesAndNames.getAttribute("content");
				content = content.replace(/&lt;/ig, '<');
				content = content.replace(/&gt;/ig, '>');
				content = content.replace(/&amp;/ig, '&');
				content = content.replace(/&quot;/ig, '\"');
				content = content.replace(/&apos;/ig, '\'');

				//alert(content);
				document.getElementById(statesandnames).innerHTML = content; 
			}
			
		}
	}

	
	var samples = [];
	function Sample(x1, x2, y, name)
	{
		this.x1 = x1;
		this.x2 = x2;
		this.y = y;
		this.name = name;
		this.getX1 = function(){return x1;};
		this.getX2 = function(){return x2;};
		this.getY = function(){return y;};
		this.getName = function(){return name;};
	}
	
	var xmlhttpcp;
	function cpResponseHandler()
	{
		if(xmlhttpcp==null) return;
		if (xmlhttpcp.readyState==4)
		{
			//alert('xmlhttpcp.readyState==4, xmlhttpcp.responseText='+xmlhttpcp.responseText);
			//alert('1:imgdatalist='+imgdatalist);
			var imgdatalist = xmlhttpcp.responseXML.getElementsByTagName("imgdatalist")[0];
			//alert('2:imgdatalist='+imgdatalist);
			if(imgdatalist!=null)
			{
				var imgdata = imgdatalist.getElementsByTagName("imgdata")[0];

				ml=imgdata.getAttribute("ml");
				mr=imgdata.getAttribute("mr");
				mt=imgdata.getAttribute("mt");
				mb=imgdata.getAttribute("mb");

				miny=imgdata.getAttribute("miny")*1;
				maxy=imgdata.getAttribute("maxy")*1;
				
				valuetype=imgdata.getAttribute("vt");
				ct=imgdata.getAttribute("ct");
				xax=imgdata.getAttribute("xax");
				
				samples = [];
				var sampleList = imgdatalist.getElementsByTagName("sample");
				if(sampleList!=null) if(sampleList.length>0)
				{
					samples = new Array(sampleList.length);
					for(var i=0; i<sampleList.length; i++)
					{
						var p=sampleList[i], x1=p.getAttribute("x1"),x2=p.getAttribute("x2"),y=p.getAttribute("y"), name=p.getAttribute("name");
						samples[i] = new Sample(x1,x2,y,name);
					}
					updateCurrentPoint();
				}
			}
		}	
	}
	function updateCurrentPoint()
	{
	    if( (clickX+5)>=ml && (clickX-5)<=(cimgw-mr) && (clickY+5)>=mt && (clickY-5)<=(cimgh-mb))
	    {
	    	var sampleFound=false;
	    	if(samples!=null)
	    	{
	    		for(i=0; i<samples.length; i++)
	    		{
	    			if( clickX>=samples[i].getX1() && clickX<=samples[i].getX2())
	    			{
	    				if(xax>0 || clickY>=samples[i].getY() )
	    				{
		    				//showCurrentPointHelp(cpx, cpy, 'x:'+samples[i].getX()+', y:'+samples[i].getY(), 5000);
		    				//showCurrentPointHelp(samples[i].getX(), samples[i].getY(), samples[i].getName(), 5000);
		    				showCurrentPointHelp(cpx, cpy, samples[i].getName(), 60000);
		    				sampleFound=true;
		    				break;
	    				}
	    			}
	    		}
	    	}
	    	if(!sampleFound)
	    	{
	    		if(ct>0)
	    		{
					var val = (miny + (1 - (clickY-mt) / (cimgh-mt-mb) ) * (maxy-miny))*1.0;
					if(valuetype=="int") showCurrentPointHelp(cpx, cpy, val.toFixed(0), 5000);
					else if(valuetype=="float")showCurrentPointHelp(cpx, cpy, val.toFixed(1), 5000);
					else if(valuetype=="hhmm")
					{
						var h=Math.floor(val);
						var m=(val-h)*60; m=m.toFixed(0); if(m<10) m='0'+m;
						var hhmm = h + ":" + m;
						showCurrentPointHelp(cpx, cpy, hhmm, 5000);
					}
	    		}
			    else hideCurrentPointHelp();
	    	}
	    }
	    else hideCurrentPointHelp();
	}
	var ml,mr,mt,mb,miny,maxy,valuetype,ct;
	var cpx,cpy,cimgw,cimgh,clickX,clickY;
	var curobj,objsrc;
	function showCurrentPoint(e, obj)
	{
		evt = e || window.event;
		curobj=obj;
		var r = obj.getBoundingClientRect();
	 	var x=r.left, y=r.top;
		//alert('window.event.x='+window.event.x+', window.event.y=' +window.event.y);
		//alert('evt.clientX='+evt.clientX+', evt.clientY=' +evt.clientY);
		//alert('window.event.clientX='+window.event.clientX+', window.event.clientY=' +window.event.clientY);
		//alert('window.event.pageX='+window.event.pageX+', window.event.pageY=' +window.event.pageY);
		cpx=evt.clientX;cpy=evt.clientY;
		
		//alert('showCurrentPoint3');
		cimgw=obj.width;cimgh=obj.height;
	    clickX = evt.clientX-x; clickY = evt.clientY-y;

		if(obj.src==objsrc)updateCurrentPoint();
		else
		{
			objsrc=obj.src;
			xmlhttpcp=createAjaxRequest(obj.src+'&dataonly=1', cpResponseHandler);
		}
 	}  
	
	var cphelptimer;
	function showCurrentPointHelp(x, y, text, timeout)
	{
		if(text==null || text=="")return;
	 	var scr=0;
	 	if (document.body && document.body.scrollTop) scr=document.body.scrollTop;
	 	// IE5 or DTD 3.2
	 	else if (document.documentElement && !document.documentElement.scrollTop) scr=0;
	 	// IE6 +4.01 but no scrolling going on
	 	else if (document.documentElement && document.documentElement.scrollTop) scr=document.documentElement.scrollTop;
	 	// IE6 +4.01 and user has scrolled
	 	//alert(scr);
	 	y+=scr;	 	
	 	x+=20;
	 	
	 	var dialogid = "cphelpdiv";
	 	var afdFrame = document.getElementById(dialogid);
	 	if (!afdFrame) 
	 	{
	 		afdFrame = document.createElement("div");
	 		afdFrame.setAttribute("id", dialogid);
	 		afdFrame.setAttribute("style", "visibility: hidden;");
	 		afdFrame.style.opacity = 0.95;
	 		afdFrame.style.filter = 'alpha(opacity=95)';
	 		afdFrame.alpha = 95;

	 		document.body.appendChild(afdFrame);
	 	}
	 	//afdFrame.innerHTML = "<div style=\"background: url('http://www.trainit.fi/img/mask90p.png') top repeat;width:auto;height:auto;color:#000000;font-size:14px;padding:2px;border:1px solid #808080;\">"+text+"</div>";
	 	afdFrame.innerHTML = "<div style=\"width:auto;height:auto;background-color:#ffffff;color:#000000;font-size:14px;padding:2px;border:1px solid #808080;\">"+text+"</div>";
	 	//alert(afdFrame.innerHTML);
		afdFrame.style.position = "absolute";
	 	afdFrame.style.left = x + "px";
	 	afdFrame.style.top = y + "px";
	 	afdFrame.style.visibility = "visible";
	 	afdFrame.style.display = "block";
	 	afdFrame.style.zIndex = 10000;
	 	afdFrame.style.width = "auto";
	 	afdFrame.style.height = "auto";
	 	if(cphelptimer!=null) clearTimeout(cphelptimer);
		if(timeout>0) cphelptimer=setTimeout("hideCurrentPointHelp();", timeout);
	 }
	 function hideCurrentPointHelp()
	 {
		 var helpdiv = document.getElementById("cphelpdiv");
		 if(helpdiv){helpdiv.style.visibility="hidden";}	 
	 }
	

	 var xmlhttpnn,nnfieldname;
	 function checkNickname(nnfn)
	 {
		 nnfieldname=nnfn;
		 var nn = document.getElementById(nnfn).value;
		 if(nn==null) return;
		 else if(nn.length==0) return;

		 if(xmlhttpnn!=null){xmlhttpnn.abort();xmlhttpnn=null;}
		 xmlhttpnn=createAjaxRequest('registration?action=checknn&nn=' + nn, checkNickNameResponseHandler);
	 }
	function checkNickNameResponseHandler()
	{
		if(xmlhttpnn==null) return;
		if (xmlhttpnn.readyState==4)
		{
			var nnok = xmlhttpnn.responseXML.getElementsByTagName("nnresult")[0];
			if(nnok!=null)
			{
				var res=nnok.getAttribute("res");
				if(res=="ok")
				{
					document.getElementById(nnfieldname).style.color = 'green';
					document.getElementById(nnfieldname).style.textDecoration="none";
				}
				else 
				{
					document.getElementById(nnfieldname).style.color = 'red';
					document.getElementById(nnfieldname).style.textDecoration="line-through";
				}
			}
			else 
			{
				document.getElementById(nnfieldname).style.color = 'red';
				document.getElementById(nnfieldname).style.textDecoration="line-through";
			}
		}	
	}

	
	
	//not used!
//	function autoIframe(frameId)
//	{
//		try
//		{
//			frame = document.getElementById(frameId);
//			
//			//find the height of the internal page
//			//alert(document.getElementById('forum_frame'));
//			//alert(document.getElementById('forum_frame').contentWindow);
//			alert(document.getElementById('forum_frame').contentWindow.scrollHeight);
//			var the_height = document.getElementById('forum_frame').contentWindow.document.body.scrollHeight;
//			alert('the_height='+the_height);
//			document.getElementById('forum_frame').height = the_height;
//			
//			//alert('frame.contentDocument=' + frame.contentDocument);
//			//alert('frame.contentWindow=' + frame.contentWindow + ', frame.contentWindow.height=' + frame.contentWindow.height);
//			//alert('frame.contentWindow.document =' + frame.contentWindow.document );
//			//alert('frame.contentWindow.document.body.scrollHeight =' + frame.contentWindow.document.body.scrollHeight );
//			//alert('frame.contentWindow.body=' + frame.contentWindow.body + ', frame.contentWindow.body.scrollHeight=' + frame.contentWindow.body.scrollHeight);
//			//alert('frame.style.height='+frame.style.height);
//			//innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
//			//alert(innerDoc);
//			//objToResize = (frame.style) ? frame.style : frame;
//			//objToResize.height = innerDoc.body.scrollHeight + 10;
//			//document.getElementById('rightcontainer').height = innerDoc.body.scrollHeight + 10;
//			//document.getElementById('forum').height = innerDoc.body.scrollHeight + 10;
//			alert('END:aaaautoIframe(' + frameId + ')...');
//		}
//		catch(err)
//		{
//			window.status = err.message;
//		}
//	}
	
	var xmlhttposc
	function saveSportColor(id, color)
	{
		//alert("id="+id+", color="+color)
		if(xmlhttposc!=null){xmlhttposc.abort();xmlhttposc=null;}
		xmlhttposc=createAjaxRequest('ownsports?action=save&id=' + id + "&color=" + color, saveSportColorResponseHandler);
	}
	function saveSportColorResponseHandler()
	{
		if(xmlhttposc==null) return;
		if(xmlhttposc.readyState==4)
		{
			//alert(xmlhttposc.responseText);			
		}
	}
	
	
	
	
	function resizeWoCells(min)
	{
		var elsa, elsth, i, j, maxd,max;

		//get max height...
		elsth=document.getElementsByTagName("div");
		for (i=0; i<elsth.length; i++)
		{
			if(elsth[i].className=="workoutrow" || elsth[i].className=="eatingrow")
			{
				elsa=elsth[i].childNodes;
				max=min;
				maxd=min;

				for (j=0; j<elsa.length; j++)
				{
					if(elsa[j].className=="workoutcell" || elsa[j].className=="eatingcell")
					{
						var h = elsa[j].scrollHeight;
						if(j>0 && h>max) max=h;
						else if(h>maxd) maxd=h;
					}
				}

				//if(max>30) 
				max += 15;
				max = Math.max(max, maxd);
				//alert('max='+max+',maxd='+maxd);
				for (j=0; j<elsa.length; j++)
				{
					if(elsa[j].className=="workoutcell" || elsa[j].className=="eatingcell")
					{
						elsa[j].style.height = max + 'px';
					}
				}
			}
		}
	}