var selectedPiece;
var lastCurrent;
var matchesFound = 0;
var totalMatches;
var theactKwords = [];


var theBottom = [];

var realArr = [];

var theIDs = ['one','two','three','four','five','six','seven','eight','nine','ten'];


function getRandom(theobject)
{
var thesecond = false;
var theNewBottom = [];
var times = 0;
var theRN;
var checkUsed = [];
totalMatches = 0;
var theKwords = [];

realArr = [];

for(var h = 0;h<10; h++)
	{
	
	theactKwords[h].style.display = "none";
	theactKwords[h].innerHTML = "hi";
	document.getElementById(theIDs[h]).style.display = "none";
	document.getElementById(theIDs[h]).innerHTML = "hi";
	
	}
totalMatches = theobject.length;





matchesFound = 0;
while(times<(totalMatches * 2))

{


if(!thesecond)
{

theRN =  Math.floor(Math.random() * (totalMatches));
while(theRN == totalMatches) theRN =  Math.floor(Math.random() * (totalMatches));
for(var d=0; d<checkUsed.length; d++)
{
  if((typeof(checkUsed[d]) == "number") && (theRN === checkUsed[d]))
  {
  theRN =  Math.floor(Math.random() * (totalMatches));
  while(theRN == totalMatches) theRN =  Math.floor(Math.random() * (totalMatches));
  d = -1;
  }
}
checkUsed[checkUsed.length] = theRN;
theKwords[theKwords.length] = theRN;
++times;
if(times == totalMatches)
{
checkUsed = new Array();
thesecond = true;

}
}
if(thesecond)
{


theRN =  Math.floor(Math.random() * (totalMatches));
while(theRN == totalMatches) theRN =  Math.floor(Math.random() * (totalMatches));
for(var e=0; e<checkUsed.length; e++)
{
  if((typeof(checkUsed[e]) == "number") && (theRN === checkUsed[e]))
  {
    theRN =  Math.floor(Math.random() * (totalMatches));
    while(theRN == totalMatches) theRN =  Math.floor(Math.random() * (totalMatches));
    e = -1;
  }


}

checkUsed[checkUsed.length] = theRN;
theNewBottom[theNewBottom.length] = theRN;
++times;

}

}


for(var f=0; f<totalMatches; f++)
{
realArr[f] =  theobject[f].knownw;

theBottom[theNewBottom[f]].className = f.toString();
theBottom[theNewBottom[f]].innerHTML = theobject[f].neww;

theactKwords[theKwords[f]].innerHTML = theobject[f].knownw;
}
for(var g = 0;g<totalMatches; g++)
	{
	theactKwords[g].style.display = "block";
	document.getElementById(theIDs[g]).style.display = "block";
	
	}
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}


            function handleReadyState(o, callback) {
			              var poll = window.setInterval(
			                function() {
			                  if(o && o.readyState == 4) {
			                    window.clearInterval(poll);
			                    if ( callback ){
			                      callback(o);
			                    }
			                  }
			                },
			                50
			              );
            }

              function getXHR() {
                var http;
                try {
                  http = new XMLHttpRequest;
                  getXHR = function() {
                    return new XMLHttpRequest;
                  };
                }
                catch(e) {
                  var msxml = [
                    'MSXML2.XMLHTTP.3.0',
                    'MSXML2.XMLHTTP',
                    'Microsoft.XMLHTTP'
                  ];
                  for (var i=0, len = msxml.length; i < len; ++i) {
                    try {
                      http = new ActiveXObject(msxml[i]);
                      getXHR = function() {
                        return new ActiveXObject(msxml[i]);
                      };
                      break;
                    }
                    catch(e) {}
                  }
                }
                return http;
              }

       function clickResp(method, uri, callback, postData) {
       				theactKwords[0].style.backgroundColor = "yellow";
       				theactKwords[1].style.backgroundColor = "yellow";
       				theactKwords[2].style.backgroundColor = "yellow";
       				theactKwords[3].style.backgroundColor = "yellow";
       				theactKwords[4].style.backgroundColor = "yellow";
       				theactKwords[5].style.backgroundColor = "yellow"; 
       				theactKwords[6].style.backgroundColor = "yellow";
       				theactKwords[7].style.backgroundColor = "yellow";
       				theactKwords[8].style.backgroundColor = "yellow";
       				theactKwords[9].style.backgroundColor = "yellow";
       				
       				


	                 var http = getXHR();
	                 http.open(method, uri, true);
	                 handleReadyState(http, callback);
	                 http.send(postData || null);
	                 return http;

          }






function checkPiece(evt)
{
  var currentPiece;
  // if(selectedPiece) selectedPiece.style.backgroundColor = "yellow";
  evt = evt || window.event;
  var target = evt.target || evt.srcElement;
  currentPiece = target;
  lastCurrent = selectedPiece;

    if(!selectedPiece) {

    if(!((currentPiece.id == undefined) || (currentPiece.id == null)  || (currentPiece.id == "")))
  {
	return;
	}
     selectedPiece = currentPiece;
     selectedPiece.style.backgroundColor = "green";
     return;
 }

if(!((selectedPiece.id == undefined) || (selectedPiece.id == null)  || (selectedPiece.id == "")))
  {
	return;
  }
  if((currentPiece.id == undefined) || (currentPiece.id == null)  || (currentPiece.id == ""))
  {


	selectedPiece.style.backgroundColor = "yellow";

 	 selectedPiece = currentPiece;
 	 selectedPiece.style.backgroundColor = "green";

 	  return;
 	  }



 if(!selectedPiece) {

 selectedPiece = currentPiece;
 selectedPiece.style.backgroundColor = "green";
 return;
 }

var thisisit = parseInt(target.className);





var pattern = new RegExp("(^|\\s)"+realArr[thisisit]+"(\\s|$)");


if ( pattern.test(lastCurrent.innerHTML) )

  {

    matchesFound++;

    if(matchesFound == totalMatches)
    {
      alert('You found them all! Great game!');
      selectedPiece.style.backgroundColor = "lime";
      currentPiece.innerHTML = currentPiece.innerHTML + " --- " + selectedPiece.innerHTML;

      selectedPiece = null;

    }else{
      alert('good match!');

      selectedPiece.style.backgroundColor = "lime";
      currentPiece.innerHTML = currentPiece.innerHTML + " --- " + selectedPiece.innerHTML;
      var theArray = [];
      theArray = currentPiece.innerHTML.split("---");

      if(theArray.length >2)
      {
      matchesFound--;
      currentPiece.innerHTML = currentPiece.innerHTML.substring(0,currentPiece.innerHTML.lastIndexOf("---"))

      }

      selectedPiece = null;

    }
  }else{
    if(!(currentPiece.id == undefined) || !(currentPiece.id == null)  || !(currentPiece.id == ""))
    {
	alert('sorry, not a match!');
	}
    selectedPiece = lastCurrent;

  }

}

window.onload=function()
{
  var el = document.getElementById('pieces');
  el.onclick = checkPiece;

  var elB = document.getElementById('pieces2');
  elB.onclick = checkPiece;



       addEvent(document.getElementById("theButton"), 'click', function() {
	             clickResp('GET',
              'wordsfile' + (document.getElementById("theTextbox")).value + '.txt',
              function(o) {
                var theVal = eval(o.responseText);
                getRandom(theVal);

                // set all li innerText and also set answer li classNames

              })});




 theactKwords = getElementsByClass("kword");



  theBottom[0] = (document.getElementById("one"));
  theBottom[1] = (document.getElementById("two"));
  theBottom[2] = (document.getElementById("three"));
  theBottom[3] = (document.getElementById("four"));
  theBottom[4] = (document.getElementById("five"));
  theBottom[5] = (document.getElementById("six"));
  theBottom[6] = (document.getElementById("seven"));
  theBottom[7] = (document.getElementById("eight"));
  theBottom[8] = (document.getElementById("nine"));
  theBottom[9] = (document.getElementById("ten"));

  realArr[0] = "2";
  realArr[1] = "3";
  realArr[2] = "9";
  realArr[3] = "4";
  realArr[4] = "7";
  realArr[5] = "6";
  realArr[6] = "1";
  realArr[7] = "5";
  realArr[8] = "8";
  realArr[9] = "10";
 



}