var currentTimer = 0;
var cacheResults = new LocalHash();

function Autocomplete() {
		var searchTerm = $('searchString').value;
		if(searchTerm=="") {
			removeInfo();
		}else if(searchTerm.length == 1) {
        	var result = cacheResults[searchTerm];
        	if(result) {
        		createInfo(result);
        	}else {
        		loadJSON(searchTerm);
        	}
        } else if (searchTerm.length == 2) {
            clearTimeout(currentTimer);
            var result = cacheResults[searchTerm];
        	if(result) {
        		createInfo(result);
        	}else {
        		currentTimer = setTimeout("loadJSON('" + searchTerm + "')", 1000);
        	}
            
        }else {
        	clearTimeout(currentTimer);
            var result = cacheResults[searchTerm];
        	if(result) {
        		createInfo(result);
        	}else {
        		 currentTimer = setTimeout("loadJSON('" + searchTerm + "')", 250);
        	}
        }
}

function loadJSON(searchTerm) {
    // Create a new UL that we can use to store the search results, as well as blank newLI and newlink
    var theUL = document.createElement("ul");
    var newLI, newlink;
    // Turn search query to lowercase so we can compare easily
    var search = $('searchString').value.toLowerCase();
    // New list
    var list = "New List";
    // Did we find an item?
    var foundItem = false;
    // Grab the JSON file to initiate search
    var host = location.protocol + "//" + location.host; 
    if(location.href.indexOf("/Tritone") > -1) host = host + "/Tritone";

    var xhr=createXHR();
    var sUrl = host + "/search/?searchString=" + search + "&host=json";
    xhr.open("GET", sUrl, true);
	xhr.onreadystatechange=function(){
        if (xhr.readyState == 4) 
           {
                list = eval('(' + xhr.responseText + ')');
                list = list.searchResults;
                if(list.categories.length == 0) { // No results!
                       // Create link
                      newresult = document.createElement("li");
                      // Give it a URL reference
                      newresult.innerHTML = "<a>No Results.  Try again?</a>";
                      theUL.appendChild(newresult);
                }
                for(i=0;i<list.categories.length;i++){      // For each category
                    //alert(list.groups[i].events.length);
                      for(g=0;g<list.categories[i].groups.length;g++) {  // For each group
                          for(e=0;e<list.categories[i].groups[g].events.length;e++) { // For each event
                              var eventLI = false;  // Did we make an LI?  Set to false for default
                              for(p=0;p<list.categories[i].groups[g].events[e].participants.length;p++) { // For each participant
                                          if(!eventLI) {
                                                // If we have not created an LI yet, then it's a new group, so let's make the group header LI first
                                                newlink = document.createElement("a");   // New link
                                                newlink.setAttribute('href', host + '/markets/' + list.categories[i].publicKey + '/' + list.categories[i].groups[g].publicKey + '/event/' + list.categories[i].groups[g].events[e].publicKey );
                                                newLI = document.createElement("li");
                                                newLI.className = "eventLI";
                                                newlink.innerHTML = list.categories[i].groups[g].events[e].name;
                                                newLI.appendChild(newlink);
                                                theUL.appendChild(newLI);
                                                eventLI = true;
                                          }

                                          // Create link
                                          newlink = document.createElement("a");
                                          // Give it a URL reference
                                          var newUrl = list.categories[i].groups[g].events[e].participants[p].ref;
                                          var eventUrl = list.categories[i].groups[g].events[e].ref;
                                          var firstPart = newUrl.substr(0, newUrl.indexOf("host/json/"));
                                          var secondPart = newUrl.substr(newUrl.lastIndexOf("host/json/")+10);
                                          var eventPart = eventUrl.substr(eventUrl.lastIndexOf("/"));
                                          var marketDetails = document.createElement('p');
                                          newlink.setAttribute('href', firstPart + secondPart + eventPart);




                                          var lowest="$999999";
                                          for(num = 0; num < list.categories[i].groups[g].events[e].participants[p].markets.length; num++) {
                                              if(list.categories[i].groups[g].events[e].participants[p].markets[num].lowestOfferToSell != null) {
                                                  var t1 = lowest.toString().replace(/[^0-9.]/g,'');
                                                  var t2 = list.categories[i].groups[g].events[e].participants[p].markets[num].lowestOfferToSell.pricePerUnit.toString().replace(/[^0-9.]/g,'');

                                                  if(parseFloat(t2) < parseFloat(t1))
                                                        lowest = list.categories[i].groups[g].events[e].participants[p].markets[num].lowestOfferToSell.pricePerUnit;
                                              }
                                          }
                                          newLI = document.createElement("li");
                                          newLI.className = "toggler";
                                          newLI.setAttribute('onmouseover', '(function() {var mySlide = new Fx.Slide("'+ list.categories[i].groups[g].shortName.toLowerCase() + list.categories[i].groups[g].events[e].shortName.toLowerCase() + list.categories[i].groups[g].events[e].participants[p].shortName.toLowerCase() + '");mySlide.toggle();}).delay(75)');
                                          newLI.setAttribute('onload', 'var mySlide = new Fx.Slide("'+ list.categories[i].groups[g].shortName.toLowerCase() + list.categories[i].groups[g].events[e].shortName.toLowerCase() + list.categories[i].groups[g].events[e].participants[p].shortName.toLowerCase() + '");mySlide.hide();');
                                          newlink.innerHTML = "<em>" + list.categories[i].groups[g].events[e].participants[p].name + "</em><span> (" + list.categories[i].groups[g].events[e].participants[p].markets.length + ")</span>";
                                          marketDetails.innerHTML = "Prices starting at " + lowest;

                                          var newDiv = document.createElement("div");
                                          newDiv.className="element";
                                          newDiv.id = list.categories[i].groups[g].shortName.toLowerCase() + list.categories[i].groups[g].events[e].shortName.toLowerCase() + list.categories[i].groups[g].events[e].participants[p].shortName.toLowerCase();


                                          theUL.appendChild(newLI);
                                          
                                          theUL.appendChild(newDiv);
                                          // Stick link in the LI
                                          newLI.appendChild(newlink);
                                          // Add the sub-list to the LI
      //                                    newLI.appendChild(subUL);
                                          newLI.appendChild(marketDetails);
                          }
                        }
                    }
                }
               
                if(search == "") {
                	removeInfo();
                }else {
                	createInfo(theUL, search, host);
                	cacheResults[searchTerm]= theUL;
                }
           }

    }
	xhr.send(null);
}

function createInfo(theUL, search, host) {
	var findBox = document.getElementById('searchResults'); // the find box
    var viewAllResults = document.createElement("div");
    viewAllResults.className = 'suggest-viewall';
    var allLink = document.createElement("a");
    allLink.setAttribute('href', host + '/search/?searchString=' + search);
    allLink.innerHTML ='View All Search Results';
    findBox.style.display = 'block';
	findBox.innerHTML = "";
	findBox.appendChild(theUL);
	findBox.appendChild(viewAllResults).appendChild(allLink);	
}

function removeInfo() {
	document.getElementById('searchResults').style.display = 'none';
}

function createXHR(){
    var request = false;
        try {
            request =  new XMLHttpRequest();
        }
        catch (err2) {
            try {
                request = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (err3) {
                try {
                    request = new ActiveXObject('Msxml2.XMLHTTP');
                }
                    catch (err1)
                    {
                        request = false;
                    }
            }
        }
    return request;
}

function LocalHash()
{
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}
	   
		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
};
	