window.onload=gameSetup;

var index;
var objBox;
var box;
var iTimesAnimate;
var blnGameStarted;
var wrongClicks;
var TotalDisplay;
var adImages = new Array("/images/game/flower_1.jpg","/images/game/flower_2.jpg","/images/game/flower_3.jpg");

var globscore=0;
var globtime=0;

index=10;
blnGameStarted = false;
wrongClicks=0;
TotalDisplay = 0;

function gameSetup(){
	flashfix();
	if(document.getElementById('btnStart')){
		animate();
		//getHighScores();
	}
}


function changeColorOn(abc){
	abc.color="white";
	abc.backgroundColor="black"
}
function changeColorOff(abc){
	abc.color="black";
	abc.backgroundColor="white"
}
function animate(){

	//var allNodes=d	

	document.getElementById('btnStart').disabled = true;
	if(index < 102){
		if(document.getElementById('cell'+(index-1))){
			document.getElementById('cell'+(index-1)).style.backgroundImage='';
		}
		if(document.getElementById('cell'+index)){	
			var randnum=Math.round((Math.random()*3));
			document.getElementById('cell'+index).style.backgroundImage='url(/images/game/flower_'+randnum+'.jpg)';
		}
		
		setTimeout('animate()',75);
		index = index + 1;
	}else{
		//setTimeout('document.getElementById("cell101").style.backgroundImage="url(/images/game/white.jpg)"',75);
		initialize();
	}
}

function checkClick(objBox1)
{
	if(blnGameStarted){
		objBox = objBox1;
		if(objBox.backgroundImage == "url(/images/game/flower_1.jpg)" || objBox.backgroundImage == "url(/images/game/flower_2.jpg)" || objBox.backgroundImage == "url(images/flower_3.jpg)"){
			globscore++
			document.buzzy.txtScore.value = globscore;
		}else{
			wrongClicks = wrongClicks + 1;
			objBox.backgroundImage='url(/images/game/red.jpg)';
			setTimeout('objBox.backgroundImage = ""',200);
		}
	}
}



function getRandom(){
	return (Math.round(Math.random()*(87-9)))+9;
}

function randOrd(){
	return (Math.round(Math.random())-0.5); 
} 

function highlightBox(){
	if(blnGameStarted){
		box = getRandom();
		adImages.sort(randOrd);
		//document.all[box].style.backgroundColor = "yellowgreen";
		document.getElementById("cell"+box).style.backgroundImage='url(' + adImages[1] + ')';
		TotalDisplay = TotalDisplay + 1;
		document.getElementById('grid').style.backgroundImage='';
		//setTimeout('document.all[box].style.backgroundColor = "white"',700);
		setTimeout('document.getElementById("cell"+box).style.backgroundImage=""',700);
		setTimeout('highlightBox()',800);
	}
}

function startTime(){
	if(globtime != 0){
		globtime--;
		document.buzzy.txtTime.value =globtime;
		setTimeout('startTime()',1000);
	}else{
		//insert 
		var score=globscore;
		var element=document.getElementById('highscores');
		var message='<h1>Well Done!</h1><p>You scored '+score+ " out of " +TotalDisplay 
		message+="<br /> No. of missed fruit clicks: " + wrongClicks+"</p>";
		message+="<p>If you would like to enter our competition please fill in the form below</p>";
		message+="<form method='post' id='highscoreform' action='/javascript/highscrores.php'>"
		message+="<label>Nick Name*</label><input id='hs_name' name='00_nickname' value=''/>"
		message+="<label>Real Name*</label><input id='hs_01name' name='01_Name' value=''/>"
		message+="<label>Email Address*</label><input id='hs_03email' name='03_Email' value=''/>"
		message+="<label>Telephone Number</label><input id='hs_name' name='04_Tel' value=''/>"
		message+="<label>Your Address</label><textarea name='05_address'></textarea>"
		message+="<br /><input type='button' value='send' onclick='sendHighScore()'>";
		
		element.innerHTML=message;
		wrongClicks=0;
		TotalDisplay=0;
		document.buzzy.btnStart.disabled = false;
		blnGameStarted = false;
	}
}

function initialize(){
	blnGameStarted = confirm('Are you ready to start testing your reflexes??')
	if(blnGameStarted){
		globtime=30;
		document.buzzy.txtTime.value = globtime;
		globscore=0;
		document.buzzy.txtScore.value = globscore;
		setTimeout('startTime()',10);
		highlightBox();
	}else{
		document.buzzy.btnStart.disabled = false;
	}
}

function getHighScores(){
	var myConn = new XHConn();
	var savingData="func=getHighScores";
	myConn.connect("/javascript/highscores.php", "POST", savingData, showHighScores);
}

function showHighScores(sentData){
	var insertArea=document.getElementById('highscores');
	//alert(sentData.responseText);
	var data=eval(sentData.responseText);
	var html="<p>"+data[1]+"</p>";
	var hsinfo=data[0];
	for(i=0;i<hsinfo.length;i++){
		 html="<label>"+hsinfo[i][1]+"</label>"+hsinfo[i][0]+"<br />"+ html;
	}	
	insertArea.innerHTML="<h2>High Scores</h2>"+html;	
}

function sendHighScore(){
	var savingData="func=addHighScore";
	var form=document.getElementById('highscoreform');
	savingData+="&00_score="+globscore;
	savingData+="&"+buildPOST('highscoreform'); 
	if(document.getElementById('hs_01name').value && document.getElementById('hs_name').value && document.getElementById('hs_03email').value){
		var myConn = new XHConn();
		myConn.connect("/javascript/highscores.php", "POST", savingData, showHighScores);
	}else{
		alert ("You must fill out all the elements marks with a * before sending this form");		
	}
}



//ajax
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function buildPOST(theFormName) {
	theForm = document.getElementById(theFormName);
	var qs = ''
	for (e=0;e<theForm.elements.length;e++) {
		if (theForm.elements[e].name!='') {
			var name = theForm.elements[e].name;
			qs+=(qs=='')?'':'&';
			if(theForm.elements[e].type=="checkbox"){
				qs+= name+'='+escape(theForm.elements[e].checked);
			}else{
				qs+= name+'='+escape(theForm.elements[e].value);			
			}
		}
	}
	qs+="\n";
	return qs
}


function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

//JSON Parser = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};