// parameters
var oSVGDoc;
var iElasticity = 1.5; // Elasticity of rubber band lower = more powerfull
var iPillSpacing = 5; // closeness of pills
var aPills = new Array(11);  // array of pills
var iPillRenewRate = 200; // speed with which pills are recycled 200 = 5secs
var aBugs = new Array(10);  // array of bugs
var iSmartPillRate = 0.1;
var iMusicVolume = 1;
var iEffectsVolume = 0.5;
var iMaxPills = 20;
var BgMusicMaxValue;
var iSpeedFactor;  // pixels per 40th of a second ( slowest speed = 1x, fastest = 3x )
var iBugSpawnRate;  // this figure is out of 1 with 40 test per second ex: a value of 0.01 = 40% chance of bug spawn per second
var iPillBounces = 6;

// vars
var iPillRenewCounter;
var bElasticSelected = false;
var CurrentlyActivePill = "";  // used to keep track of pill being dragged
var svgversion = -1;
var BgMusicCounter;  // used to control speed of bgmusic
var BgMusic = 0;  // store current bgmusic to play
var bSpawnBugs = false;
var bGameOver = false;
var aStars = new Array();	


// browser settings
var is_ie = false;
var NavVersion = -1;

// debug
var bDebug = false;

var agt = navigator.userAgent.toLowerCase().split(";");
is_ie = (agt[1].indexOf("msie") != -1);
if(is_ie)
	NavVersion = parseFloat(agt[1].substring(5,agt[1].length));
else
	alert('Warning this Navigtor is of unknown type, the application may not work correctly');


function startUp()
{
	// fill arrays
	SetBugArray();
	SetPillArray();
	
	iEffectsVolume = document.all('Volume').value;
	oSVGDoc = document.embeds['Ping1'].getSVGDocument();
	
	//StartGame();
}

function SetBugArray()
{
	for(i=0;i<aBugs.length;i++)
	{
		aBugs[i] = false;
	}
}

function SetPillArray()
{
	for(i=0;i<aPills.length;i++)
	{
		aPills[i] = false;
	}
}

function StartGame()
{
	DebugOut('start');
	if(document.embeds['Ping1'] == null)
    		return;
    	else
    		oSVGDoc = document.embeds['Ping1'].getSVGDocument();
    	
    	// hide messages
    	var obj = oSVGDoc.getElementById('illaT');
    	obj.setAttribute('y',200);
    	obj = oSVGDoc.getElementById('rawlaT');
    	obj.setAttribute('y',200);
    	obj = oSVGDoc.getElementById('K1');
    	obj.setAttribute('y',200);
    	obj = oSVGDoc.getElementById('K2');
    	obj.setAttribute('y',200);
    	obj = oSVGDoc.getElementById('startButton');
    	obj.setAttribute('y',200);
    	obj = oSVGDoc.getElementById('replayButton');
    	obj.setAttribute('y',200);
    	
    	// show game end button
    	obj = oSVGDoc.getElementById('EndGameTemplate');
    	obj.setAttribute('y',0);
    	
    	// reset vars
    	
    	bSpawnBugs = true;
	bGameOver = false;
	BgMusicMaxValue = 20;
	BgMusicCounter = BgMusicMaxValue;
	iSpeedFactor = 1;
	iBugSpawnRate = 0.02;
	iPillRenewCounter = iMaxPills - aPills.length;
	
    	ResetActiveElements();
    	
    	// spawn pills
	var i = 0;
	while (i < aPills.length)
	{
		SpawnPill(iPillSpacing,i);
		aPills[i] = false;			
		i++;
	}
	PositionPills();
			
	// initialize pill counter
	document.all('PillCounter').value = iMaxPills;
	document.all('score').value = 0;
	document.all('HighestScore').value = 0;
	SetVolume();
	
	oNode = oSVGDoc.getElementById('GameOverTemplate');
	oNode.setAttribute('x',-200);
	oNode.setAttribute('y',-200);
}

function SetVolume()
{
	oAudioList = oSVGDoc.getElementsByTagName('a:audio');
	for(i=0;i<oAudioList.length;i++)
	{
		DebugOut(oAudioList.item(i).id);
		oAudioList.item(i).setAttribute('volume',0);
		if (iEffectsVolume > 0)
		oAudioList.item(i).setAttribute('volume',parseFloat(oAudioList.item(i).getAttribute('volume')) + iEffectsVolume);
		
	}
	//oAudio = oSVGDoc.getElementsById('
}


function ResetElastic()
{
	var obj = oSVGDoc.getElementById('elastic');
	obj.setAttribute('d','M45,5 L45,30 L45, 55');	
	if(bElasticSelected)
	{
	bElasticSelected = false;
	//alert('here');
	playSound('twing');
	}
}

function SpawnPill(lx,id)  // functions called by the html must be declared on the page cannot be in the svg 
{
	DebugOut('spawnPill');
	var obj = oSVGDoc.getElementById('template1')
	var oNewNode = obj.cloneNode(false);
	oNewNode.setAttribute ('x', lx);
	oNewNode.setAttribute ('Dx', 0);
	oNewNode.setAttribute ('Dy', 0);
	oNewNode.setAttribute ('id', id);
	oNewNode.setAttribute ('class', 'pill');
	oNewNode.setAttribute ('RenewCounter', iPillRenewRate);
	oNewNode.setAttribute ('SmartPill', 'false');
	oNewNode.setAttribute ('BounceCounter', iPillBounces);
		
	obj = oSVGDoc.getElementById('elasticGraphic');
	oNewNode = obj.appendChild(oNewNode);
}

function PositionPills()  // re-orders the pill pile and removes spaces
{
//alert('position');
	var tempY = 55;
	for(i=0;i<aPills.length;i++)
	{
		var oPill = oSVGDoc.getElementById(i);
		if(!(oPill == null))
		{
			if((aPills[i] == false) && (parseInt(oPill.getAttribute('RenewCounter')) == iPillRenewRate))
			{
				//DebugOut(tempY);
				oPill.setAttribute('y',tempY);
				tempY -= iPillSpacing;
			}
		}
			
	}
}

function DebugOut(msg)
{
	if(bDebug)
	{var obj = document.all('debug');
	obj.innerText += ' ' + msg;}
}


function Redraw()
{
	if(!(bSpawnBugs))
	{
		if(bGameOver)
		{
			var oNode = oSVGDoc.getElementById('GameOverTemplate');
			var iCounter = oNode.getAttribute('Counter');
			DebugOut(iCounter);
			if(iCounter < 3)
			{
				bGameOver = false;
				var obj = oSVGDoc.getElementById('replayButton');
				obj.setAttribute('y',57);
			}
			else
			{
				iCounter--;
				oNode.setAttribute('Counter',iCounter);
	
				var iScale = iCounter * 0.4;
				var iX = 230;
				var iY = 20 - (iScale * 1);
			
				var sTransformText = 'translate(' +iX + ' ' +iY + ') scale(' + iScale + ')  rotate(-10) translate(-' +iX + ' -' +iY +')';
				DebugOut(sTransformText);
				oNode.setAttribute('transform',sTransformText);
			}
			
		}
		return;
	}
	
	if(Math.random() < iBugSpawnRate)  // spawn bugs
	{
		var i = 0;
		while(i < aBugs.length)
		{
			if(!(aBugs[i]))
			{
				SpawnBug(i);
				aBugs[i] = true;
				i = aBugs.length;
			}
			i++;
		}
	}
	
	for(i=0;i<aPills.length;i++)  // deal with pills
	{
		var oPill = oSVGDoc.getElementById(i);
		
		if (aPills[i])  // move
		{
			oPill.setAttribute('x',parseInt(oPill.getAttribute('x')) + parseInt(oPill.getAttribute('Dx')));
			oPill.setAttribute('y',parseInt(oPill.getAttribute('y')) + parseInt(oPill.getAttribute('Dy')));
			if(!(PillBoundries(oPill)))
				RemovePill(oPill);
		}
		else	// renew
		{
			var iRenew = parseInt(oPill.getAttribute('RenewCounter'));
					
			if (iRenew < 2)
			{
				if (iPillRenewCounter > 0)  // reach 0 so don't renew
					RenewPill(oPill);
			}
			else
			{
				if(iRenew < iPillRenewRate)
				{
//						//alert(iRenew);
					iRenew--;
					oPill.setAttribute('RenewCounter',iRenew);
				}
			}
		}

	}
	
	for(i=0;i<aBugs.length;i++)  // deal with bugs
	{
		if (aBugs[i])
		{
			var oBug = oSVGDoc.getElementById('bugs' + i);
			oBug.setAttribute('x',parseFloat(oBug.getAttribute('x')) + parseFloat(oBug.getAttribute('Dx')));
			oBug.setAttribute('y',parseFloat(oBug.getAttribute('y')) + parseFloat(oBug.getAttribute('Dy')));
			if(BugBoundries(oBug))
			{	
				var iDeathCounter = parseInt(oBug.getAttribute('DeathCounter'));		
				if(iDeathCounter==6) // check if bug is dying	
				{
					//alert(iDeathCounter);
					var iAnimCounter = parseInt(oBug.getAttribute('AnimationCounter'));
					var iTotalFrames = parseInt(oBug.getAttribute('TotalFrames'));
					
					if (iAnimCounter < iTotalFrames)
						iAnimCounter++;
					else
						iAnimCounter = 1;
					
					oBug.setAttribute('AnimationCounter',iAnimCounter);
					oBug.setAttribute('xlink:href',oBug.getAttribute('BugType') + iAnimCounter + '.gif');
				}
				else
				{
					//alert(iDeathCounter);
				 	if(iDeathCounter==1)
				 		RemoveBug(oBug);
				 	else	
				 		oBug.setAttribute('DeathCounter',iDeathCounter-1);	
				}
			}
			else
			{
        				SpawnStar(parseInt(oBug.getAttribute('x')),parseInt(oBug.getAttribute('y')),0.5 + (Math.random() * 2));
        				           				
				var sBugType = oBug.getAttribute('BugType');
				var score = -1;
				if(sBugType == 'spider')
					score = -5;
				if(sBugType == 'scorpion')
				{
					score = -10;
				}
				Scoring(score);
				RemoveBug(oBug);
				j = Math.floor(Math.random()*3);
        				DebugOut('ow' + j);
        				playSound('ow' + j);
			}
			
		}
	}
	
	DetectCollisions();
	if(BgMusicCounter == 1) {
		if(BgMusic == 4)
			BgMusic=1;
		else
			BgMusic++;
		playSound('bg' + BgMusic);
		BgMusicCounter = BgMusicMaxValue;
	}
	else
		BgMusicCounter--;
	
	for(i=0;i<aStars.length;i++) {
		if(aStars[i] > 1) {
			aStars[i]--;
			//DebugOut(aStars[i]);
		} else {
			oStar = oSVGDoc.getElementById('star' + i);
			if(!(oStar==null))
				RemoveStar(oStar);
		}	
		
	}
}

function RenewPill(oPill) {
	DebugOut('renewPill');
	oPill.setAttribute ('x', iPillSpacing);
	oPill.setAttribute ('Dx', 0);
	oPill.setAttribute ('Dy', 0);
	oPill.setAttribute ('RenewCounter', iPillRenewRate);
	oPill.setAttribute ('BounceCounter', iPillBounces);
	// smart Pills
	if(Math.random() < iSmartPillRate) {
		oPill.setAttribute('SmartPill','true');
		oPill.setAttribute('class','smartPill');
	} else {
		oPill.setAttribute('SmartPill','false');
		oPill.setAttribute('class','pill');
	}
	iPillRenewCounter--;
	PositionPills();
}

function SpawnBug(id)
{
	var iSpeed; // 3 random speeds
	iSpeed = Math.floor(Math.random() * 10);
	if (iSpeed < 8)
		if(iSpeed < 4)
			iSpeed = 1;
		else
			iSpeed = 2;
	else
		iSpeed = 3;
	
	var obj = oSVGDoc.getElementById('BugTemplate')
	var oNewNode = obj.cloneNode(false);
	oNewNode.setAttribute ('x', 390);
	oNewNode.setAttribute ('y', Math.floor(Math.random() * 50));
	oNewNode.setAttribute ('Dx', 0 - (iSpeed * iSpeedFactor));
	oNewNode.setAttribute ('Dy', 0);
	oNewNode.setAttribute ('DeathCounter', 6);
	oNewNode.setAttribute ('id', 'bugs' + id);
	oNewNode.setAttribute ('AnimationCounter', 0);
	
	var ibugType = Math.floor(Math.random() * 10);
	if ((ibugType < 1) && (parseInt(document.all('PillCounter').value) < 15)) {
		oNewNode.setAttribute ('BugType', 'scorpion');
		oNewNode.setAttribute ('TotalFrames', 2);
	} else {
		if (ibugType < 7) {
			oNewNode.setAttribute ('BugType', 'RedBug');
			oNewNode.setAttribute ('TotalFrames', 2);
		} else {
			oNewNode.setAttribute ('BugType', 'spider');
			oNewNode.setAttribute ('TotalFrames', 3);
		}
	}
	
		
	obj = oSVGDoc.getElementById('targetRange');
	oNewNode = obj.appendChild(oNewNode);
}

function RemovePill(obj) {
	DebugOut('removePill');
	//container = oSVGDoc.getElementById('elasticGraphic');
	//container.removeChild(obj);
	
	aPills[obj.getAttribute('id')] = false;
	//DebugOut('remove=' + obj.getAttribute('id') + 'active=' + aPills[obj.getAttribute('id')]);
	obj.setAttribute('x', -10);
	obj.setAttribute('Dx', 0);
	obj.setAttribute('Dy', 0);
	obj.setAttribute('RenewCounter',iPillRenewRate - 1);
	// alert(obj.getAttribute('RenewCounter'));
	
	/*if(bElasticSelected)
		ResetElastic();*/
	
	var oPillCounter = document.all('PillCounter');			
	if (oPillCounter.value > 1)
		oPillCounter.value = parseInt(oPillCounter.value) - 1;
	else
		GameOver();
}

function RemoveBug(obj) {
	DebugOut('RemoveBug');
	var id = obj.getAttribute('id');
	//alert(id.substring(id.lastIndexOf('s') + 1,id.length));
	aBugs[parseInt(id.substring(id.lastIndexOf('s')+1,id.length))] = false;
	container = oSVGDoc.getElementById('targetRange');
	container.removeChild(obj);
}

function DetectCollisions() {
	if(!(bSpawnBugs)) return;
	
	for(i=0;i<aBugs.length;i++) {
		if(aBugs[i]) {
			for(j=0;j<aPills.length;j++) {
				if(aPills[j]) {
					var oPill = oSVGDoc.getElementById(j);
					var PillX = parseInt(oPill.getAttribute('x'));
					var PillY = parseInt(oPill.getAttribute('y'));
					var PillD = 4; // radius
					var oBug = oSVGDoc.getElementById('bugs' + i);
					var BugX = parseFloat(oBug.getAttribute('x'));
					var BugY = parseFloat(oBug.getAttribute('y'));
					var BugWidth = parseInt(oBug.getAttribute('width'));
					var BugHeight = parseInt(oBug.getAttribute('height'));
					if((((PillX + PillD) > BugX) && ((PillX + PillD) < (BugX + BugWidth))) || (((PillX - PillD) > BugX) && ((PillX - PillD) < (BugX + BugWidth)))) {
						if(((PillY + PillD) > BugY && (PillY + PillD) < (BugY + BugHeight)) || ((PillY - PillD) > BugY && (PillY - PillD) < (BugY + BugHeight))) {
							if(oPill.getAttribute('SmartPill') == 'true') { // kill all
								for(i=0;i<aBugs.length;i++) {
									if(aBugs[i]) {
										var tempBug = oSVGDoc.getElementById('bugs' + i);
										SplatBug(tempBug);
									}
										
								}
								RemovePill(oPill);
								playSound('shockperson');
								shake(6);
								return;
							} else {
								SplatBug(oBug);
								playSound('splat');
							}
							RemovePill(oPill);
						}
					}
				}
			}
		}
	}
}

function SplatBug(oBug) {
	oBug.setAttribute('xlink:href','splatWithBits.gif');
	oBug.setAttribute('DeathCounter',5);
	oBug.setAttribute('Dx',0);
	oBug.setAttribute('Dy',0);
	var sBugType = oBug.getAttribute('BugType');
	var score = 1;
	if(sBugType == 'spider') score = 5;
	
	if(sBugType == 'scorpion') {
		score = 5;
		document.all('PillCounter').value = parseInt(document.all('PillCounter').value) + 10;
		iPillRenewCounter += 10;
	}
	Scoring(score);
}

function PillBoundries(obj) {

	var _X = parseInt(obj.getAttribute('x'));
	var _Y = parseInt(obj.getAttribute('y'));
	var _Bounced = false;

	if (_X > 400) return false;
	
	if (_X < 0) {
		_Bounced = true;
		obj.setAttribute('Dx',-(parseInt(obj.getAttribute('Dx'))))
		playSound('springboing');
	}
	
	if ((_Y < 0) || (_Y > 60)) {
		_Bounced = true;
		obj.setAttribute('Dy',-(parseInt(obj.getAttribute('Dy'))))
		playSound('springboing');
	}
	
	if(_Bounced) {
		_count = parseInt(obj.getAttribute('BounceCounter'));
		if( _count < 0)	{
			//alert(_count);
			return false;
		} else {
		//alert(_count);
			obj.setAttribute('BounceCounter', _count-1 )
		}
	}
	
	return true;
}

function BugBoundries(oBug) {
	var ret = false;
	var tempX = parseFloat(oBug.getAttribute('x'));
	var tempY = parseFloat(oBug.getAttribute('y'));
	if ((tempX > 70) && (tempX < 400) && (tempY > 0) && (tempY < 60))
		ret = true;
	return ret;
}


function playSound(sID) {
    	
    	oSound = oSVGDoc.getElementById(sID);
    	/*oNewSound = oSound.cloneNode(false);
    	container = oSVGDoc.getElementById('targetRange');
    	container.removeChild(oSound);
    	oNewSound.setAttribute('repeatCount','indefinite');
    	container.appendChild(oNewSound);
    	
    	alert(sound.getAttribute('id'));*/
        oSound.beginElement();
        
}

function Scoring(int){
	var scr = parseInt(document.all('score').value);
	scr += int;
	document.all('score').value = scr;
	BgMusicMaxValue = 20;
	iSpeedFactor = 1;
	iBugSpawnRate = 0.02;
	if (scr > 20)	{
		BgMusicMaxValue = 17;
		iBugSpawnRate = 0.04;
	}
	if (scr > 40)	{
		BgMusicMaxValue = 15;
		iSpeedFactor = 2;
	}
	if (scr > 60)	{
		BgMusicMaxValue = 13;
		iBugSpawnRate = 0.06;
	}
	if (scr > 80)	{
		BgMusicMaxValue = 10;
		iSpeedFactor = 3;
	}
	if (scr > 100)	{
		BgMusicMaxValue = 7;
		iBugSpawnRate = 0.08;
	}
	if (scr > 150) 	{
		BgMusicMaxValue = 5;
		iSpeedFactor = 4;
	}
	if (scr > 200) 	{
		BgMusicMaxValue = 3;
		iSpeedFactor = 5;
	}
	
	var oHighestScore = document.all('HighestScore');
	if ((scr) > parseInt(oHighestScore.value))
		oHighestScore.value = scr;
	if(scr < -20) {
		GameOver();
	}
}

function shake(n) {
	if (window.top.moveBy) {
		for (i = 10; i> 0; i--) {
			for (j = n; j> 0; j--) {
				window.top.moveBy(0,i);
				window.top.moveBy(i,0);
				window.top.moveBy(0,-i);
				window.top.moveBy(-i,0);
			}
		}
	}
}

function CheckPillCounter() {
	var oPillCounter = document.all('PillCounter');
	DebugOut('changed counter');
	if(oPillCounter.value < 1)
		GameOver();
}

function ResetActiveElements() {
	for(i=0;i<aPills.length;i++)
	{
		var oPill = oSVGDoc.getElementById(i);
		if(!(oPill == null))
		{
			var container = oSVGDoc.getElementById('elasticGraphic');
			container.removeChild(oPill);
		}
			
	}
	for(i=0;i<aBugs.length;i++)
	{
		var oBug = oSVGDoc.getElementById('bugs' + i);
		if(!(oBug == null))
			RemoveBug(oBug);
	}
	SetBugArray();	
	SetPillArray();
	CurrentlyActivePill = "";
	ResetElastic();
}

function GameOver() {	
	DebugOut('over');
	
        // Reset game status
        
        bSpawnBugs = false;
        bGameOver = true;
	
	ResetActiveElements();

	// hide end game button
	obj = oSVGDoc.getElementById('EndGameTemplate');
    	obj.setAttribute('y',200);
    			
	// display game over		

	oNode = oSVGDoc.getElementById('GameOverTemplate');
	oNode.setAttribute('x',120);
	oNode.setAttribute('y',5);
	oNode.setAttribute('Counter',10);


	// start animation	
	var iScale = 10 * 0.4;
	var iX = 230;
	var iY = 20 - (iScale * 1);
		
	var sTransformText = 'translate(' +iX + ' ' +iY + ') scale(' + iScale + ') translate(-' +iX + ' -' +iY +') rotate(-10)';
	oNode.setAttribute('transform',sTransformText);
	playSound('gameover');
				            	
}

function SpawnStar(iX,iY,iScale) {
	oNode = oSVGDoc.getElementById('StarTemplate');
	oNode = oNode.cloneNode(false);
	
	oNode.setAttribute('x',iX);
	oNode.setAttribute('y',iY);
	iX = iX+5;
	iY = iY+5;
	
	var sTransformText = 'translate(' +iX + ' ' +iY + ') scale(' + iScale + ') translate(-' +iX + ' -' +iY +')';
	// DebugOut(sTransformText);
	oNode.setAttribute('transform',sTransformText);
	oNode.setAttribute('id','star' + aStars.length);
	// DebugOut(oNode.getAttribute('id'));
	aStars[aStars.length] = 40;
	
	var container = oSVGDoc.getElementById('targetRange');
        	container.appendChild(oNode);
        	
}

function RemoveStar(oStar) {
	var container = oSVGDoc.getElementById('targetRange');
	container.removeChild(oStar);
}