// Global Variables
var diameter = 61;
var radius = (diameter-1)/2;
var radius_mark = 10;
var backgroundWidth = 400;
var backgroundHeight = 400;
var timeInterval = 500;
var useMozEffect = true;

var maxArrayLength = 13;
var lArray = new Array(maxArrayLength);
var tArray = new Array(maxArrayLength);
var sArray = new Array(maxArrayLength);
var x;
var y;
var curLevel;
var clickCount;
var score;
var score1;
var timer_1;
var timer_2;
var timer_3;

// Functions
function addEvent(obj, evType, fn)
{
	if(obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	}else if(obj.attachEvent)
	{
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}else
	{
		return false;
	}
}

function removeEvent(obj, evType, fn)
{
	if(obj.removeEventListener)
	{
		obj.removeEventListener(evType, fn, false);
		return true;
	}else if(obj.detachEvent)
	{
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	}else
	{
		return false;
	}
}

function addText(obj, str)
{
	if(navigator.appName.indexOf("Explorer") > -1)
	{
		obj.innerText=str;
	}else
	{
		obj.textContent=str;
	}
}

function GetAbsoluteLocationEx(element)
{
    if ( arguments.length != 1 || element == null )
    {
        return null;
    }
    var elmt = element;
    var offsetTop = elmt.offsetTop;
    var offsetLeft = elmt.offsetLeft;
    var offsetWidth = elmt.offsetWidth;
    var offsetHeight = elmt.offsetHeight;
    while( elmt = elmt.offsetParent )
    {
        if ( elmt.style.position == 'absolute' || elmt.style.position == 'relative'
            || ( elmt.style.overflow != 'visible' && elmt.style.overflow != '' ) )
        {
            break;
        }
        offsetTop += elmt.offsetTop;
        offsetLeft += elmt.offsetLeft;
    }
    return { absoluteTop: offsetTop, absoluteLeft: offsetLeft,
        offsetWidth: offsetWidth, offsetHeight: offsetHeight };
}

function ShowCircle(i,isOK)
{
	var al=GetAbsoluteLocationEx(document.getElementById("div_background"));
	var l=al.absoluteLeft;
	var t=al.absoluteTop;

	document.getElementById("div_circle").style.left=l+lArray[i];
	document.getElementById("div_circle").style.top=t+tArray[i];
	document.getElementById("div_circle").style.visibility="visible";

	if(!(navigator.appName.indexOf("Explorer") > -1))
	{
		if(useMozEffect && isOK)
		{
			clearTimeout(timer_2);
			timer_2=setTimeout("ShowCircle2('0')",timeInterval/8);
			clearTimeout(timer_3);
			timer_3=setTimeout("HideCircle2('100')",timeInterval-timeInterval/8-timeInterval/8);
		}else
		{
			document.getElementById("div_circle").style.MozOpacity=1;
		}
	}
}

function ShowCircle2(o)
{
	if(o<=100)
	{
		document.getElementById("div_circle").style.MozOpacity=o/100;
		timer_2=setTimeout("ShowCircle2('"+(o+20)+"')",timeInterval/48);
	}else
	{
		document.getElementById("div_circle").style.MozOpacity=1;
	}
}

function HideCircle()
{
	if(!(navigator.appName.indexOf("Explorer") > -1))
	{
		document.getElementById("div_circle").style.MozOpacity=0;
	}

	document.getElementById("div_circle").style.visibility="hidden";
}

function HideCircle2(o)
{
	if(o>=0)
	{
		document.getElementById("div_circle").style.MozOpacity=o/100;
		timer_3=setTimeout("HideCircle2('"+(o-20)+"')",timeInterval/48);
	}else
	{
		document.getElementById("div_circle").style.MozOpacity=0;
	}
}

function ShowMark()
{
	var al=GetAbsoluteLocationEx(document.getElementById("div_background"));
	var l=al.absoluteLeft;
	var t=al.absoluteTop;

	document.getElementById("div_mark").style.left=l+x-radius_mark;
	document.getElementById("div_mark").style.top=t+y-radius_mark;
	document.getElementById("div_mark").style.visibility="visible";
}

function HideMark()
{
	document.getElementById("div_mark").style.visibility="hidden";
}

function DrawBar(isok)
{
	var str="<table><tr>";

	for(var i=0;i<curLevel+1;i++)
	{
		if(i>=clickCount)
		{
			str+="<td class='unknown'>?</td>";
		}else if(i==clickCount-1 && !isok)
		{
			str+="<td class='err'>:(</td>";
			ShowCircle(i,false);
			ShowMark();
		}else
		{
			score1=Math.round(60+(radius*radius-sArray[i])*40/(radius*radius));
			if(score1<60)
			{
				str+="<td class='bad'>"+score1+"</td>";
			}else
			{
				str+="<td class='ok'>"+score1+"</td>";
			}
		}
	};

	str+="</tr></table>";

	document.getElementById("div_bar").innerHTML=str;
}

function div_background_attach()
{
	addEvent(document.getElementById("div_background"),"click",div_background_onclick);
	document.getElementById("div_background").style.cursor="crosshair";
}

function div_background_detach()
{
	removeEvent(document.getElementById("div_background"),"click",div_background_onclick);
	document.getElementById("div_background").style.cursor="not-allowed";
}

function div_background_onclick(e)
{
	var al=GetAbsoluteLocationEx(document.getElementById("div_background"));
	var l=al.absoluteLeft;
	var t=al.absoluteTop;

	x=e.clientX+document.body.scrollLeft-l;
	y=e.clientY+document.body.scrollTop-t;
	if(document.body.clientLeft)
	{
		x-=document.body.clientLeft;
	}
	if(document.body.clientTop)
	{
		y-=document.body.clientTop;
	}

	sArray[clickCount]=(x-lArray[clickCount]-radius)*(x-lArray[clickCount]-radius)+(y-tArray[clickCount]-radius)*(y-tArray[clickCount]-radius);

	score1=Math.round(60+(radius*radius-sArray[clickCount])*40/(radius*radius));

	clickCount++;

	if(score1<0)
	{
		DrawBar(false);
		div_background_detach();
		GameOver();
	}else
	{
		score+=score1;
		GameHint("Level: "+curLevel+" Score: "+score,"Next Level");

		DrawBar(true);
		if(clickCount>curLevel)
		{
			div_background_detach();
			GameComplete();
		}
	}
}

function GameHint(str1,str2)
{
	addText(document.getElementById("div_hint"),str1);
	addText(document.getElementById("div_button_1"),str2);
}

function GameInit()
{
	document.getElementById("div_background").style.width=backgroundWidth+2;
	document.getElementById("div_background").style.height=backgroundHeight+2;
	document.getElementById("div_background").style.paddingLeft=5;
	document.getElementById("div_background").style.paddingTop=5;

	var al=GetAbsoluteLocationEx(document.getElementById("div_background"));
	var l=al.absoluteLeft;
	var t=al.absoluteTop;

	document.getElementById("div_hint").style.left=l+backgroundWidth-144;
	document.getElementById("div_hint").style.top=t+parseInt(document.getElementById("div_background").style.paddingTop);
	document.getElementById("div_hint").style.visibility="visible";

	var al=GetAbsoluteLocationEx(document.getElementById("div_username"));
	var t=al.absoluteTop;
	document.getElementById("div_hint").style.top=t;

	GameHint("","Start Game");
	document.getElementById("div_bar").style.display="none";
	document.getElementById("div_hint").style.display="none";
	document.getElementById("div_button").style.display="none";
	document.getElementById("div_form").style.display="block";
	curLevel = 1;


	loadScore(10);
}

function GameGo()
{
	var pattern = /^\s*(\S.*\S)\s*$/;
	if(pattern.test(document.getElementById("username").value.toLowerCase()))
	{
		document.getElementById("username").value=RegExp.$1;
		//addText(document.getElementById("div_background")," Username: "+RegExp.$1);
		addText(document.getElementById("div_username")," Username: "+RegExp.$1);
		document.getElementById("div_bar").style.display="block";
		document.getElementById("div_hint").style.display="block";
		document.getElementById("div_button").style.display="block";
		document.getElementById("div_form").style.display="none";

		clickCount=-1;
		DrawBar(true);
	}else
	{
		document.getElementById("username").value="";
		document.getElementById("username").focus();
		alert("Please input your name !");
	}
}

function GameStart()
{
	clearTimeout(timer_1);

	clickCount = 0;

	if(curLevel==1)
	{
		score = 0;
	}

	HideCircle();
	HideMark();

	DrawBar(true);

	GameHint("Level: "+curLevel+" Score: "+score,"Next Level");
	document.getElementById("div_button_1").disabled=true;

	for(var i=0;i<curLevel+1;i++)
	{
		lArray[i]=Math.round(Math.random() * (backgroundWidth-diameter)) + 1;
		tArray[i]=Math.round(Math.random() * (backgroundHeight-diameter)) + 1;
		setTimeout("ShowCircle('"+i+"','true')",i*timeInterval);
	}
	setTimeout("HideCircle();div_background_attach();",(curLevel+1)*timeInterval);
}

function GameOver()
{
	GameHint("Level: "+curLevel+" Score: "+score,"Restart Game");
	document.getElementById("div_button_1").disabled=false;

	if(score>=document.getElementById("minTopScore").value)
	{
		updateScore(document.getElementById("username").value,score,curLevel);
	}

	curLevel = 1;
}

function GameComplete()
{
	curLevel++;
	GameAutoNextLevel(3);
	document.getElementById("div_button_1").disabled=false;
}

function GameAutoNextLevel(i)
{
	if(i==0)
	{
		GameStart();
	}else
	{
		GameHint("Level: "+(curLevel-1)+" Score: "+score,"Next Level ("+i+")");
		timer_1=setTimeout("GameAutoNextLevel('"+(i-1)+"')",1000);
	}
}

addEvent(window,"load",GameInit);
