arousal = 0;
valence = 0;
total = 0;
score = 0;
init_partner_delay = 2;
overlapbonus = 0;
extrabonus = 0;
total_bonus = 0;
partner_arousal = 0;
partner_valence = 0;
var seconds_count = 0;
prevscore = 0;
dacurscore = 0;
total_score = 0;
prevdiff = 0;
prev_val = 0;
prev_ar = 0;
partner_display_frequency = 2;
total_game_time = 95;
thecurrenttime = 95;
seconds_count = 0;
secstocount = 4;
x_arousal =0;
y_valence = 0;
function startSample()
{
	removeChildren(document.getElementById('test-board'));
	str += '<div id="game-board" class="game_active">\n';
	var str = '<img src="images/partner-image-1.png" id="partner-img-1" />\n';
	str += '<img src="images/partner-image-2.png" id="partner-img-2" />\n';
	str += '<img src="images/board/transparent-layer.png" id="gboard" class="cursor_crosshair" />';
	str += "</div>";
	div = createDiv(str);
	document.getElementById('test-board').appendChild(div);
	//load song//
	samplesongloc = 'sounds/sample.mp3';
	setTimeout("createPlayer('player1',samplesongloc,'true','0')", 1500);
	cdwn();
	//load sample data//
	//Http request stuff
	http = getHTTPObject();
	http.open("GET", "sampledata.php", true);
	http.onreadystatechange = handleHttpResponse;
	http.send(null);
	
}

function handleHttpResponse() {
	usrdata = new Array();
if (http.readyState == 4) {
	  if (http.responseText.indexOf('invalid') == -1) {
	 var response = http.responseXML.documentElement;
	 x=response.getElementsByTagName("point");
	 for (i=0;i<x.length;i++)
    {
		  usrdata[i] = x[i].firstChild.data;
	 }
  }
}
}

function removeChildren(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
};
function createDiv(opt_text, opt_className) {
var el = document.createElement("div");
if (opt_text) {
el.innerHTML = opt_text;
}
if (opt_className) { el.className = opt_className; }
return el;
};

function startgame(){
songlen = 97;
 imagewidth = 200;
 imagedecrement = imagewidth/(songlen+10);
	//Activate Gameboard
	document.getElementById('gboard').setAttribute("onmousemove", "getcurPoint(event)");
	document.getElementById('test-board').className = "game_active";
	document.getElementById('gboard').className = "cursor_crosshair";
	//start countdown
	gamecountdown(songlen);
}

function gamecountdown()
{
	if(thecurrenttime > 0) {
		imagewidth = imagewidth - imagedecrement;
		//get Sample Point//
		partner_cur_point = usrdata[seconds_count].split(",");
		partner_arousal = Number(partner_cur_point[0]);
		partner_valence = Number(partner_cur_point[1]);
		
		//increment seconds//
		seconds_count = seconds_count+1;
		var partner_counter = thecurrenttime % partner_display_frequency;		

		//sendmycoords();

		if (thecurrenttime <= total_game_time-1) 
		{
			calculate_score();
		}
		if(imagewidth <= 10)
		{
			imagewidth = 10;
		}
		showbeacon("partner-img-1","images/partner-image-1.png",imagewidth);
		
		//showscore();

		if(partner_counter == 0 && thecurrenttime < total_game_time - init_partner_delay) 
		{
			showpartnerimage("images/partner-image-2.png",imagewidth);
		}

		thecurrenttime = thecurrenttime - 1;
		var t = setTimeout("gamecountdown()",1000);
		gameClockText = "<h2><p>Time left: "+thecurrenttime+" Current Score: "+total_score.toFixed(2)+" <span style='font-size:10px; color:green'>+ "+total.toFixed(2)+"</span></p></h2>\n";
		document.getElementById('sampletimer').innerHTML = gameClockText; //thecurrenttime;
	
		//Sample Notes
		if(thecurrenttime == 90)
		{
			var samplenotes = "At this point. Notice the change in intensity within the song. Gradually reduce your intensity value.";
			document.getElementById('samplestatus').innerHTML = samplenotes;
		}
		if(thecurrenttime == 75)
		{
			var samplenotes = "Notice the song gradually gets less and less intense. Also decide whether the song is upbeat or sad.";
			document.getElementById('samplestatus').innerHTML = samplenotes;
		}
		if(thecurrenttime == 55)
		{
			var samplenotes = "The closer you and your partner(the red cursor) agree, the more points you get. You recieve bonus points when you overlap.";
			document.getElementById('samplestatus').innerHTML = samplenotes;
		}
		if(thecurrenttime == 25)
		{
			var samplenotes = "As time goes on, notice you and your partner's cursor shrink in size. This makes it tougher to overlap, but you recieve more points when you do.";
			document.getElementById('samplestatus').innerHTML = samplenotes;
		}

	}
	else {
		//Turn off music player
		document.getElementById('player1').style.display = "none";

		//Remove mouse over attribute
		document.getElementById('gboard').removeAttribute("onmousemove");
		document.getElementById('test-board').className = "game_disabled";

		endgame();
	}
}
function endtxt()
{
	if (total_score<100)
	{
	retval = "Not bad. Remember, you want to try to agree with your partner as closly as possible. Give the sample game one more try, or start playing the game now!";
	}
	if (total_score<300 && total_score>100)
	{
		retval = "Nice Work! You've got the hang of it. Remember you get more points the more you and your partner agree. Play the sample game again or start playing the live game now!";

	}
	if (total_score>300)
	{
	retval = "Nice Work! You are a natural at this! Go ahead and get started playing the live game!";
	}
	return retval;
}
function endgame()
{
	removeChildren(document.getElementById('test-board'));
	var txt = endtxt()
	endtext = "<p>"+txt+"</p>";
	endtext += "<p><a href='#' onClick='startSample()'>Play Sample Game again</a></p>";
	endtext += "<p><a href='play.php'>Play Mood Swings Now!</a></p>";
	var div = createDiv(endtext);
	document.getElementById('test-board').appendChild(div);
}
function showbeacon(imageid,imagesrc,imgwidth)
{
	document.getElementById(imageid).src = imagesrc;
	document.getElementById(imageid).style.width = imgwidth+"px";
	var xoffset = Math.floor(imgwidth/2);
	var imgleft = x_arousal + 200 - imgwidth + xoffset; 
	var imgtop = 200 - xoffset - y_valence;
	document.getElementById(imageid).style.top = imgtop+"px";
	document.getElementById(imageid).style.left = imgleft+"px";
	document.getElementById(imageid).style.visibility = "visible";
	opacity(imageid,100,0,800);	
};

function showpartnerimage(imagesrc,imgwidth)
{
	document.getElementById('partner-img-2').src = imagesrc;
	document.getElementById('partner-img-2').style.width = imgwidth+"px";
	var xoffset = Math.floor(imgwidth/2);
	var imgleft = partner_arousal + 200 - imgwidth + xoffset; 
	var imgtop = 200 - xoffset - partner_valence;
	document.getElementById('partner-img-2').style.top = imgtop + "px";
	document.getElementById('partner-img-2').style.left = imgleft + "px";
	document.getElementById('partner-img-2').style.visibility = "visible";
	  //document.getElementById('partner-img-2').style.width = dacurwidth+"px";

	
	opacity('partner-img-2',100,0,800);

}

function calculate_score()
{
	overlapbonus = 0;
	extrabonus = 0;
	//get distance 
	var dist = Math.sqrt( (y_valence - partner_valence)*(y_valence - partner_valence) + (x_arousal - partner_arousal)*(x_arousal - partner_arousal) );
	var radius = imagewidth/2;
	if(dist <= radius)
	{
		var diff = radius - dist;
		overlapbonus = diff/3;
	}
	//calculate score
	score = 565/dist;

	//Check to see if partner got closer to you for additional bonus
	if(diff < prevdiff)
	{
		val_dif = Math.abs(prev_val - y_valence);
		ar_dif = Math.abs(prev_ar - x_arousal);
		if(val_dif <= 10 && ar_dif <= 10)
		{
			//You and your partner got closer to one another
			extrabonus = 10;
		}
	}
	score = score/10;
	total_bonus = (extrabonus + overlapbonus)/10;
	total = total_bonus + score;
	
	total_score = total_score + total;
	//Check to see if there is a 
	//dacurscore = score.toFixed(2)//score.toFixed(2);

}

function cdwn() {
	var cntdown = document.getElementById('sampletimer');
	var statusdiv = document.getElementById('status');
	if( secstocount == 0)
	{ 
		startgame();
		statusdiv.innerHTML = "<center><img id='notetimer' src='note.jpg' onload='javascript:sendEvent("+'"volume"'+",currentVolume + 100);' /></center>";
	}else {
	cntdown.innerHTML = "<center><h2 style='color:blue'><font size='5'>"+secstocount+"</font></h2><center>";
		secstocount=secstocount - 1;
		setTimeout("cdwn()", 1100);
	}
}

function createPlayer(playerid,songlocation,start,vol){
	//Load music player
	var player = new SWFObject("mp3player.swf","mplayer","320","0","9");
	player.addVariable("file",songlocation);
	player.addVariable("autostart",start);
	player.addVariable("enablejs","true");
	player.addVariable("volume",vol);
	player.addVariable("javascriptid","mplayer");
	player.addVariable("bufferlength","1");
	player.write(playerid);

}

function getHTTPObject() {

  var xmlhttp;

  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {

    try {

      xmlhttp = new XMLHttpRequest();

    } catch (e) {

      xmlhttp = false;
    }
  }
  return xmlhttp;
}//end gethttpobject

function getcurPoint(evt)
{
  // grab the x-y pos.s if browser is NS
    xpoint = evt.layerX 
    ypoint = evt.layerY 	
	//timeleft = thecurrenttime;

	//Get the coordinates of the point selected
	x_arousal = Number(xpoint - 200);
	y_valence = Number(200 - ypoint);
	//sendmycoords();
}