//	Egg-Traction
//	 for DEBUGGED @ http://www.truplex.com
//	written by Stephen Battey - October 1997



//--------------------------------------------------------------
//     Some bottom level functions that I find very useful
//--------------------------------------------------------------



function ToHex(number) {
//			function returns the 2digit hex equivalent
//			of 'number' - for some reason, the .toString(16)
//			method returns  :  instead of  a  !!!

	Ref="0123456789abcdef"
	fdig=Math.floor(number/16)
	sdig=number-(fdig*16)
	return Ref.substring(fdig,fdig+1)+Ref.substring(sdig,sdig+1)
}



function ToDec(text) {
//			function returns the 2digit decimal
//			equivalent of 'text'

	Ref="0123456789abcdef"
	temp=16*(Ref.indexOf(text.substring(0,1)))
	temp+=Ref.indexOf(text.substring(1,2))
	return temp
}



function NumText(v,width,use) {
//			returns the number 'v' in a text string of minimum
//			length 'width', preceeding spaces being filled with
//			the character specified in 'use'

	post=v.toString()
	pre=""
	uselen=width-post.length
	for (i=1; i<=uselen; i++) {
		pre+=use
	}
	return pre+post
}



function mMODn(m,n) {
//			Function returns the least
//			residue of :   m (mod n)

	while ( m>=n )
		m=m-n
	return m
}



now4Random = new Date()
mRandom=1024
cRandom=55
aRandom=13
rRandom=((now4Random.getSeconds()-1)/60)*mRandom

function Random(minv,maxv) {
//			Function returns a random number in the range
//			minv - maxv

	rRandom=mMODn(((aRandom*rRandom)+cRandom),mRandom)
	return ( ((rRandom/1024)*(maxv-minv))+minv )
}






//----------------------------------------
//     Setup Global game variables
//----------------------------------------


Hiscore=0
Score=0
Target=0
TimeM=0
TimeS=0
Level=0
Stage=0
Eggs=0

  delay = new Array()
TilePic = new Array()
for (i=1; i<12; i++) {
	  delay[i] = new Array()
	TilePic[i] = new Array()
	for (j=1; j<17; j++)
		TilePic[i][j]="RedDot.gif"
}

GameOn=false
AwaitingStart=false
AwaitingEnd=false

CurCol=0
CurRow=0

BasketTileCol = new Array();
BasketTileRow = new Array();


BasketFN="EggBasket.gif"
ShellsFN="EggShells.gif"
StrawFN="EggStraw.gif"
BucketFN="EggBucket.gif"
EggFN="EggEgg.gif"
HenFN="EggHen.gif"
ChickFN="EggChick.gif"


fileNames = new Array(StrawFN,BucketFN,BasketFN)

penScreen = new Array()
penScreen[1]="00000020000000 00000000000000 00110000000000 00110000000000 00000000000000 00000000001100 00000000001100 00000000000000 00000002000000"
penScreen[2]="00000000000000 00000000000000 00110000001100 00110000001100 00110200201100 00110000001100 00110000001100 00000000000000 00000000000000"
penScreen[3]="20011000000000 00011000000000 00011000000000 00011000000000 00011000011000 00000000011000 00000000011000 00000000011000 00000000011002"
penScreen[4]="00000000000000 00011000011000 00011000011000 00011000011000 02011000011020 00011000011000 00011000011000 00011000011000 00000000000000"
penScreen[5]="00000000000102 00000000000100 00111111100100 00100000000100 00100000000100 00100000000100 00100111111100 00100000000000 20100000000000"
penScreen[6]="00002000020000 00000000000000 01111111111110 01000000000010 01001000010010 01001000010010 01001000010010 01001111110010 00000000000000"
penScreen[7]="00000000000000 01101111110000 01000000010000 01011100010000 21010000011010 11010101111010 00010100000010 01110111111110 21200000002000"
penScreen[8]="20000000000012 11111011111010 00000000001010 01111111101010 00000000101000 11101110001010 00000010101010 00000000101010 00000010100012"




//--------------------------------------------------
//     Low-level routines for the whole program
//--------------------------------------------------



function RefreshTime() {
//			Shows the time left onto the screen

	ToShow=NumText(TimeM,2," ")+":"+NumText(TimeS,2,"0")
	document.Stats.gameTime.value=ToShow
}



function RefreshStats() {
//			Places the stats in the screen form

	f=document.Stats

	RefreshTime()
	f.level.value=NumText(Level,2," ")
	f.stage.value=NumText(Stage,2," ")
	f.target.value=NumText(Target,7," ")
	f.score.value=NumText(Score,7," ")
}



function RefreshTile(r,c,fn) {
//			Places the picture file 'fn' onto the tile specified

	ImNo = ((r-1)*16) + (c-1) + 2
	document.images[ImNo].src=fn
}



function InitialisePic() {
//			Initalises the pen for the current level

	thisPen=penScreen[mMODn(Level-1,penScreen.length-1)+1]
	
	BasketTileCol = new Array();
	BasketTileRow = new Array();

	OpenTiles=126
	curPos=0
	for (row=2; row<11; row++) {
		for (col=2; col<16; col++) {
			pfn=eval(thisPen.substring(curPos,curPos+1))
			TilePic[row][col]=fileNames[pfn]
			curPos++
			RefreshTile(row,col,TilePic[row][col])
			if ( pfn!=0 )
			{
				OpenTiles--
				if (pfn == 2)
				{
					BasketTileCol[BasketTileCol.length] = col;
					BasketTileRow[BasketTileRow.length] = row;
				}
			}
		}
		curPos++
	}
}



function ShowEggs() {
//			Displays the eggs being carried

	pfn=EggFN
	for (i=0; i<5; i++) {
		if ( i==Eggs )
			pfn="BlackDot.gif"
		document.images[i+178].src=pfn
	}
}



function ShowBaskets( fileName ) {
//			Sets the image URL of the baskets - allowing the baskets to be set to their
//      basket image or another image, say white-dot, which allows the baskets to flash.

	for (var i=0; i<BasketTileCol.length; i++)
	{
		RefreshTile( BasketTileRow[i], BasketTileCol[i], fileName );
	}
}



function EggWait() {
//			Calculates how many tiles to skip until an egg should be put in

	if ( NoOfEggs>(Level/2)+NoOfHens )
		return -1

	lowerLevel=10-(Level/2)
	if ( lowerLevel<1 )
		lowerLevel=1
	return Math.round(Random(lowerLevel,lowerLevel+20))
}






//-------------------------------------
//     Main game functions
//-------------------------------------




function NextStage() {
//			Sets variables for the next stage/level

	AwaitingEnd=false
	Stage++
	if ( Stage>3 ) {
		Stage=1
		Level++
		InitialisePic()
		NoOfShells=0
	} else {
		for (i=2; i<11; i++) {
			for (j=2; j<16; j++) {
				p=TilePic[i][j]
				if ( ( p==EggFN ) | ( p==HenFN ) | ( p==ChickFN ) ) {
					TilePic[i][j]=StrawFN
					RefreshTile(i,j,StrawFN)
					OpenTiles++
				}
			}
		}
	}
	Target=(Level*3)+2 +((Stage-1)*(Level+1))
	TotalTime=(11-Level)*Target
	if ( TotalTime<50 )
		TotalTime=50
	TimeM=Math.floor(TotalTime/60)
	TimeS=TotalTime-(60*TimeM)
	RefreshStats()
	Eggs=0
	ShowEggs()

	NoOfHens=0
	NoOfEggs=0
	ControlRow=2
	ControlCol=2
	ToNextEgg=-1

	AwaitingStart=true
	FlashTimer=window.setTimeout("AwaitStageStart()",600)
}



function EndOfLevel() {
//			Add shell bonus to score

	d=0
	if ( Stage==3 ) {
		b=0
		if ( NoOfShells>14 ) {
			b=(NoOfShells-14)*-20
			ShowStr="High wasted eggs deduction !!"
		}
		if ( NoOfShells<6 ) {
			b=475-(NoOfShells*75)
			ShowStr="Few wasted eggs bonus !"
		}
		if ( NoOfShells==0 ) {
			b=750
			ShowStr="No broken eggs bonus !!!"
		}
		if ( b!=0 ) {
			d=3000
			Score+=b
			window.status=ShowStr+"  ("+b.toString()+"pts)"
		}
	}

	window.setTimeout("NextStage()",d)
}



function EndOfStage() {
//			Add time bonus to score

	window.status="End of stage time bonus ..."
	TimeS-=10
	if ( TimeS<0 ) {
		TimeS+=60
		TimeM--
	}
	if ( TimeM<0 ) {
		TimeM=0
		TimeS=0
	}
	RefreshTime()
	Score+=Level
	document.Stats.score.value=NumText(Score,7," ")

	if ( ( TimeM>0 ) | ( TimeS>0 ) )
		window.setTimeout("EndOfStage()",200)
	else
		window.setTimeout("EndOfLevel()",1500)
}



function EndOfGame() {
//			Displays end of game message

	alert( "\n\n***************************\n       GAME  OVER\n***************************\n\n" );
	
	if (promptSubmitScore)
	{
		var scores = new Array();

		scores[0] = new HiScore( 8, Score, "Level " + Level + "; Stage " + Stage );

		promptSubmitScore( scores );
	}
	
	GameOn=false;
}








//--------------------------------------------------
//     Game control routines ran in background
//--------------------------------------------------



function AwaitStageStart() {
//			Alerts user to begin the game

	refStr="next stage"
	if ( Stage==1 ) {
		refStr="next level"
		if ( Level==1 )
			refStr="the game"
	}
	window.status="Place your cursor over a basket to begin "+refStr

	f=document.Stats
	if ( f.gameTime.value=="-----" ) {
		f.target.value=NumText(Target,7," ")
		RefreshTime()
		ShowBaskets( BasketFN );
	} else {
		f.target.value="-------"
		f.gameTime.value="-----"
		ShowBaskets( "WhiteDot.gif" );
	}

	FlashTimer=window.setTimeout("AwaitStageStart()",300)
}



function DecreaseTime() {
//			Ticks down the counter

	TimeS--
	if ( TimeS<0 ) {
		TimeS=59
		TimeM--
	}
	RefreshTime()
	CounterTimer=window.setTimeout("DecreaseTime()",1000)
}



function MainControl() {
//			Updates screen and checks for end of game

//		Check for stage win
	if ( Target==0 ) {
		clearTimeout(CounterTimer)
		AwaitingEnd=true
		window.setTimeout("EndOfStage()",750)
		return
	}
//		Check for game lose
	if ( ( ( TimeS==0 ) & ( TimeM==0 ) ) | ( OpenTiles==0 ) ) {
		clearTimeout(CounterTimer)
		window.setTimeout("EndOfGame()",500)
		return
	}

	cr=ControlRow
	cc=ControlCol
	ThisTile=TilePic[cr][cc]
	if ( ToNextEgg>0 )
		ToNextEgg--

	if ( ThisTile==StrawFN ) {
//		Convert to egg ??
		if ( ToNextEgg==0 ) {
			TilePic[cr][cc]=EggFN
			OpenTiles--
			NoOfEggs++
			d=Math.floor(5-(Level/4))
			if ( d<1 )
				d=1
			delay[cr][cc]=d
			ToNextEgg--
		}
	}
	if ( ThisTile==EggFN ) {
//		Convert to chick ??
		delay[cr][cc]--
		if ( delay[cr][cc]==0 ) {
			NoOfEggs--
			delay[cr][cc]=2
			TilePic[cr][cc]=ChickFN
		}
	}
	if ( ThisTile==ChickFN ) {
//		Convert to hen ??
		delay[cr][cc]--
		if ( delay[cr][cc]==0 ) {
			TilePic[cr][cc]=HenFN
			NoOfHens++
		}
	}
	if ( ThisTile!=TilePic[cr][cc] )
			RefreshTile(cr,cc,TilePic[cr][cc])
	if ( ToNextEgg==-1 )
		ToNextEgg=EggWait()

	ControlCol++
	if ( ControlCol>15 ) {
		ControlCol=2
		ControlRow++
		if ( ControlRow>10 )
			ControlRow=2
	}

	GameTimer=window.setTimeout("MainControl()",10)
}






//--------------------------------------------------
//     Top-level routines called by user action
//--------------------------------------------------




function Pointed(TileRow,TileCol) {
//			Decides what to do when cursor is pointed

	if ( !GameOn ){
		window.status="Press PLAY button to begin a new game."
		return
	}
	window.status=""

	if ( AwaitingEnd )
		return


	OverPic=TilePic[TileRow][TileCol]

	if ( AwaitingStart ) {
		if ( OverPic==BasketFN )
			StartGame()
		return
	}




	if ( CurCol>0 )
		RefreshTile(CurRow,CurCol,TilePic[CurRow][CurCol])
	OldRow=CurRow
	OldCol=CurCol
	CurRow=TileRow
	CurCol=TileCol
	if ( ( OverPic==StrawFN ) | ( OverPic==EggFN ) )
		RefreshTile(CurRow,CurCol,"WhiteDot.gif")

	if ( OverPic==BasketFN ) {
		Score+=Eggs*((Level+1)*5)
		Target-=Eggs
		if ( Target<0 )
			Target=0
		RefreshStats()
		Eggs=0
		ShowEggs()
		return
	}
	if ( OverPic==EggFN ) {
		if ( Eggs<5 ) {
			Eggs++
			NoOfEggs--
			ShowEggs()
			TilePic[CurRow][CurCol]=StrawFN
			OpenTiles++
		}
		return
	}
	if ( ( OverPic==StrawFN ) | ( OverPic==ShellsFN ) | ( Eggs==0 ) )
		return

	NoOfShells+=Eggs
	if ( TilePic[OldRow][OldCol]==StrawFN ) {
		OpenTiles--
		TilePic[OldRow][OldCol]=ShellsFN
		RefreshTile(OldRow,OldCol,ShellsFN)
	}
	Eggs=0
	ShowEggs()
}



function StartGame() {
//			Starts the game (that stage, that level

	AwaitingStart=false
	clearTimeout(FlashTimer)
	
	// baskets were flashing white, ensure basket images are restored
	ShowBaskets( fileNames[2] );
	
	// time and collect stats were also flashing, restore these too
	RefreshStats()
	
	CounterTimer=window.setTimeout("DecreaseTime()",1000)
	GameTimer=window.setTimeout("MainControl()",150)
}



function StartReady() {
//			Sets up game start

	if ( GameOn )
		return

	GameOn=true
	Level=0
	Stage=3
	Score=0
	NextStage()
}




function do_nothing()
{
}
