﻿var req;
var browser, version;
var detect = navigator.userAgent.toLowerCase();
if (checkIt('msie')) {
    browser = "Internet Explorer";
    version = detect.charAt(place + thestring.length);
}
function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}
function loadXMLDoc(url) {

	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
		if(req) {
		    req.onreadystatechange = processReqChange;
		    req.open("GET", url, true);
		    req.send(null);
	    }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
		if(req) {
		    req.onreadystatechange = processReqChange;
		    req.open("GET", url, true);
		    req.send();
	    }
    }	
}

function processReqChange() {

    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
			//alert(req.responseText);
            parseXML(req);

        } else {
            //alert("There was a problem retrieving the XML data:\n" + req.statusText);
			//alert(req.responseText);
        }
    }
}

function parseXML(obj) {

    var xmlDoc;

    	if(window.XMLHttpRequest && browser != "Internet Explorer") {
    	try {
		    var parser = new DOMParser();
            xmlDoc = parser.parseFromString(obj.responseText, "text/xml");
        } catch(e) {
			xmlDoc = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {       	
        	try {
          		xmlDoc = new ActiveXObject("MSXML2.DOMDocument"); 
          		xmlDoc.async = false;
		        xmlDoc.loadXML(obj.responseText.replace(new RegExp("&","g"),"&amp;"));
        	} catch(e) {
          		xmlDoc = false;
        	}
        	        	
		    if (xmlDoc.parseError.errorCode != 0) {
                var myErr = xmlDoc.parseError;
                //alert("You have error " + myErr.reason);
            }
    }
    
	if (xmlDoc) {	   
				
		var names = xmlDoc.documentElement.getElementsByTagName('n');
		var namesC = xmlDoc.documentElement.getElementsByTagName('p');
		var prices = xmlDoc.documentElement.getElementsByTagName('m');
		 
		clearPopup();
		
		if (names.length > 0) {
			popup.className = "searchResults";
			popup.id = "searchResults";
		}
		
		var isLast = false;
		var isFirst = true;
		for (i = 0; i < names.length && i <= 20; i++) {
			if (i == names.length - 1 || i == 20)
				isLast = true;
			populate(names[i].firstChild.data, prices[i].firstChild.data, namesC[i].firstChild.data, isLast, isFirst);
			isFirst = false;
		}
		
		xmlDoc = null;
	}
}

function searchInventory(input) {
    var o = document.getElementById("categoryFilter");
    if (o.selectedIndex > 1) {
        var v = o.options[o.selectedIndex].value;  
	    url  = 'ajaxCode.asp?c=' + v + '&q=' + input.value;
    } else {
	    url  = 'ajaxCode.asp?q=' + input.value;
    }
    loadXMLDoc(url); 
}

function clearPopup() {
   
	popup.className = "searchResultsEmpty";
	popup.id = "searchResultsEmpty";
	
    while (popup.childNodes.length > 0) {
        popup.removeChild(popup.childNodes[0]);
    }
}

function clearSearch() {
  
	popup.className = "searchResultsEmpty";
	popup.id = "searchResultsEmpty";
	
    while (popup.childNodes.length > 0) {
        popup.removeChild(popup.childNodes[0]);
    }
}

function populate(text, price, restOfName, isLast, isFirst) {
    
    // First <p>
	if (price == "" || price == "n/a")
		price = "&nbsp;";	
	if (restOfName == "n/a")
	    restOfName = "";
	
	var div = document.createElement('div'); 
	var div1 = document.createElement('div'); 
	var div2 = document.createElement('div'); 
	var br = document.createElement('br');
	    
	div.className = "unhighlight";
	if (isFirst) {
	    div.className = "header"
		div1.className = "l";
		div2.className = "r";
	} else if (isLast) {
		div1.className = "lb";
		div2.className = "rb";
	} else {
		div1.className = "l";
		div2.className = "r";
	}
	
	if (!isFirst) {
	    div.onmouseover = function() {
		    highlight(this);
	    }
    	
	    div.onmousedown = function() {
		    selectHighlighted();
	    }
	    div1.innerHTML = "&nbsp;<span class='fr'>" + text + "</span>" + restOfName;
	} else {								
        div1.innerHTML = "&nbsp;" + text;
    }
	div2.innerHTML = price + "&nbsp;";

    div.appendChild(div1);
    div.appendChild(div2);
    popup.appendChild(div);
    popup.appendChild(br);
}

/**
 * Handler for the "keydown" event
 */
function inputKeyDown(input, e) {
 
  if (!e) {
    e = window.event;
  }
 
  switch (e.keyCode) {
    case 40: // down arrow
      selectDown();
      return false;
    case 38: // up arrow
      selectUp();
      return false;
    default: // all other keys
      return true;
  }
}

function selectHighlighted() {

	document.searchForm.exactSearch.value = 'false';
		
	if (oldNode) {	
		var val = oldNode.firstChild.innerHTML.replace("&nbsp;", "");
		val = val.replace("&amp;", "&");
		val = val.toLowerCase();
		val = val.replace("<span class=fr>", "");
		val = val.replace("<span class=\"fr\">", "");
		val = val.replace("</span>", "");
		var regexp = new RegExp(/more results/)
		if (val.match(regexp)) {
			oldNode = false;
			document.searchForm.submit();
			return false;
		}		
		document.searchForm.searchText.value = val;
		document.searchForm.exactSearch.value = 'true';		
		oldNode = false;
	}
	
	if (document.searchForm.searchText.value != "" && document.searchForm.searchText.value.length > 2) {
		
		document.searchForm.submit();
		return false;
	}
}

/**
 * Highlights the next suggestion
 */
function selectDown() {
 
  if (oldNode && oldNode.nextSibling && oldNode.nextSibling.nextSibling) {
    highlight(oldNode.nextSibling.nextSibling);
  } else {
  	if (oldNode)
		unhighlight(oldNode);
  	oldNode = false;
    var lis = popup.getElementsByTagName('div');
    if (lis.length > 0) {
      highlight(lis[3]);
    }
  }
}

/**
 * Highlights the previous suggestion
 */
function selectUp() {
  if (oldNode && oldNode.previousSibling && oldNode.previousSibling.previousSibling) {
    if (oldNode.previousSibling.previousSibling.previousSibling != null)
        highlight(oldNode.previousSibling.previousSibling);
  } else {
  	oldNode = false;
  }
}

/**
 * Handler for the "keyup" event
 */
function inputKeyUp(input, e) {
  
  if (!e) {
    e = window.event;
  }
  
  switch (e.keyCode) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
      return true;

    case 9:  // tab
    case 13: // enter
    case 27: // esc
	  selectHighlighted();
      clearPopup();
      return false;

    default: // all other keys
      if (input.value.length >= 1)
        searchInventory(input);
      else
        clearPopup();
      return true;
  }
}

/**
 * Highlights a suggestion
 */
function highlight(node) {

  if (oldNode)
  	oldNode.className = "unhighlight";
	
  if (node)
  	node.className = "highlight";
  	  
  oldNode = node;
}

/**
 * Unhighlights a suggestion
 */
function unhighlight(node) {
  
  if (node)
  	node.className = "unhighlight";
}

var oldNode = false;

function isSearchWithinCat() {

	var result = false;
	
	result = document.searchForm.searchWithinCat.value == "true";
	
	return result;
}
