var selectedItem;
var curSelection = -1;
function KeyDownHandler( event )
{
   var key = event.keyCode;
   switch(key)
   {
       case 13: SelectSuggestion(event);
                break;
       case 40: MoveUp();
		if ( event.stopPropagation )
		{
		       event.stopPropagation();
		       event.preventDefault();
		}
                break;
       case 38: MoveDown();
		if ( event.stopPropagation )
		{
		       event.stopPropagation();
		       event.preventDefault();
		}
                break;
   }
}

function KeyPressHandler( event )
{
   var key = event.keyCode;
   switch(key)
   {
       case 27: HideDiv();
		if ( event.stopPropagation )
		{
		       event.stopPropagation();
		       event.preventDefault();
		}
                break;
       case 8:  HideDiv();
                GetSearchSuggestions(event);
                break;
       default: GetSearchSuggestions(event);
                break;
   }

}

function BodyClickHandler(event)
{
	HideDiv();
}

function HideDiv()
{
   curSelection = -1;
   var div = document.getElementById("suggestionDiv");
   if ( div )
   {
       div.style.display = "none";
   }
}

function MoveUp()
{
    var allSelections = completions;
    try
    {
        var selection = null;
        try
        {
            selection = allSelections[curSelection];
        }
        catch(e) {}

        if ( selection )
        {
            selection.style.backgroundColor = "";
	    selectedItem.style.background = "";
            selection.style.color = "black";
        }

        if ( curSelection >= allSelections.length )
            curSelection = 0;
        else
            curSelection++;

        if ( selectedItem )
        {
            selectedItem.style.backgroundColor = "";
	    selectedItem.style.background = "";
            selectedItem.style.color = "";
        }

        selection = allSelections[curSelection];
        selection.style.backgroundColor = "#736F6E";
	selection.style.background = "url(/templates/default/images/th.jpg) repeat-x scroll left bottom";
        selection.style.color = "white";
        selectedItem = selection;
        document.getElementById('searchinput').value = selectedItem.value;
    }
    catch(ex)
    {
    }
}

function MoveDown()
{
    var allSelections = completions;
    try
    {
        var selection = null;
        try
        {
            selection = allSelections[curSelection];
        }
        catch(e) {}

        if ( selection )
        {
            selection.style.backgroundColor = "";
	    selection.style.background = "";
            selection.style.color = "black";
        }

        if ( curSelection <= 0 )
            curSelection = allSelections.length - 1;
        else
            curSelection--;

        if ( selectedItem )
        {
            selectedItem.style.backgroundColor = "";
            selectedItem.style.background = "";
            selectedItem.style.color = "";
        }

        selection = allSelections[curSelection];
        selection.style.backgroundColor = "#736F6E";
	selection.style.background = "url(/templates/default/images/th.jpg) repeat-x scroll left bottom";
        selection.style.color = "white";
        selectedItem = selection;

        document.getElementById('searchinput').value = selectedItem.value;
    }
    catch(ex)
    {
    }
}

function SetSelection(element)
{
    var allSelections = completions;

    for (var selCt = 0; selCt < allSelections.length; selCt++ )
    {
        if ( allSelections[selCt] == element)
        {
            curSelection = selCt;
        }
    }

    if ( selectedItem )
    {
        selectedItem.style.backgroundColor = "";
        selectedItem.style.background = "";
        selectedItem.style.color = "";
    }

    var selection = allSelections[curSelection];
    if ( selection )
    {
        selection.style.backgroundColor = "#736F6E";
	selection.style.background = "url(/templates/default/images/th.jpg) repeat-x scroll left bottom";
        selection.style.color = "white";
        selectedItem = selection;
    }
}

function SelectSuggestion(event)
{
    var url = "http://guncanyon.com/complete/complete.php?q=" + encodeURIComponent(document.getElementById('searchinput').value);
    document.location.href = url;
}

var dataFetchInterval = null;
function GetSearchSuggestions(event)
{
    var keyPressed = event.keyCode;
    if (( keyPressed >= 65 && keyPressed <= 90 ) || ( keyPressed >= 48 && keyPressed <= 57 ) || (keyPressed == 8) || (keyPressed == 32))
    {
	if ( dataFetchInterval )
	{
		clearTimeout(dataFetchInterval);
		dataFetchInterval = null;
	}

	dataFetchInterval = setTimeout( function() {
				var searchBox = document.getElementById("searchinput");
				var value = searchBox.value;
				if ( value == "" )
				{
					HideDiv();
					return;
				}

				var urlOfSuggestService = "http://guncanyon.com/complete/complete.php?q=" + encodeURIComponent(value);
				fetchData(urlOfSuggestService);
			}, 100);
    }
}

function GetProductSuggestions(term)
{
}

function fetchData( url )
{
    var srcElem = document.createElement("script");
    document.body.appendChild(srcElem);
    srcElem.type = "text/javascript";
    srcElem.src = url;
}

function updateCompletion(object)
{
   var results = object

   var terms = [];
   if ( results.length > 1 )
   {
       terms = results[1];
   }

   RenderSuggestionDiv(terms);
}

function RenderSuggestionDiv(terms)
{
   var searchBox = document.getElementById('searchinput');
   var suggestionDiv = document.getElementById("suggestionDiv");

   if ( !suggestionDiv )
   {
	suggestionDiv = BuildSuggestionDiv(document.getElementById("search"));
   }

   suggestionDiv.style.display = "";

   while( suggestionDiv.firstChild )
   {
       suggestionDiv.removeChild(suggestionDiv.firstChild);
   }

   completions = [];
   for (var termCt = 0; termCt < terms.length; termCt++ )
   {
       var term = terms[termCt];
       var div = AddSuggestion(suggestionDiv, term);
       completions[termCt] = div;
   }

   curSelection = -1;
}

function AddSuggestion(suggestionTerms, term)
{
   var value = term.substr(0,50);
   var selectedElement = document.createElement("div");

   //Put this into the DOM before we attach event handlers.
   suggestionTerms.appendChild(selectedElement);

   selectedElement.style.cursor = "pointer";
   selectedElement.appendChild(document.createTextNode(value));
   selectedElement.value = term;
   if ( document.all )
	selectedElement.style.paddingLeft = "9px";
   else
	selectedElement.style.paddingLeft = "11px";
   selectedElement.style.fontWeight = "bold";
   selectedElement.style.fontSize= "11px";
   selectedElement.style.overflow= "hidden";

   selectedElement.onmouseover = (function(div) {
                                                   return (function(){
                                                           div.style.backgroundColor = "#736F6E";
							   div.style.background = "url(/templates/default/images/th.jpg) repeat-x scroll left bottom";
                                                           div.style.color = "white";
                                                           SetSelection(div);
                                                       });
                                                   })(selectedElement);

   selectedElement.onmouseout = (function(div) {
                                                   return (function(){
							   div.style.background = "";
                                                           div.style.backgroundColor = "";
                                                           div.style.color = "black";
                                                       });
                                                   })(selectedElement);

   selectedElement.onclick = (function(div) {
                                                   return (function(){
                                                           ReplaceSearchTerms(div.value);
                                                           HideDiv();
                                                       });
                                                   })(selectedElement);

   selectedElement.onkeyup = (function(div) {
                                                   return (function(){
                                                           if ( event.keyCode == 13 )
                                                           {
                                                               ReplaceSearchTerms(div.value);
                                                               HideDiv();
                                                           }
                                                       });
                                                   })(selectedElement);

    //selectedElement.ontouchmove = TouchMove;

    return selectedElement;
}

function BuildSuggestionDiv(parentNode)
{
   var suggestionDiv = document.createElement("div");
   suggestionDiv.style.border = "1px solid black";
   suggestionDiv.style.position = "absolute";
   suggestionDiv.style.backgroundColor= "white";
   suggestionDiv.style.color = "black";
   suggestionDiv.style.width = Math.floor(parentNode.scrollWidth/2);
   suggestionDiv.style.zIndex= "30";
   if ( document.all && !isIE8 )
   	suggestionDiv.style.marginLeft = "-187px";
   else if ( isIE8 )
   	suggestionDiv.style.marginLeft = "72px";
   else
   	suggestionDiv.style.marginLeft = "67px";

   suggestionDiv.style.textAlign= "left";
   suggestionDiv.id = "suggestionDiv";
   suggestionDiv.style.width = "298px";
   parentNode.appendChild(suggestionDiv);

   return suggestionDiv;
}

function ReplaceSearchTerms(terms)
{
   var searchBox = document.getElementById("searchinput");
   searchBox.value = terms;
}


