var req;
var win;
var changeLast = "";
var reloadMenu;
var isIE = false;

function liveSearchInit() {
	
	if (navigator.userAgent.indexOf("Safari") > 0) {
  	
		document.getElementById("Name").addEventListener("keydown", liveSearchKeyPress, false);
		
	} else if (navigator.product == "Gecko") {
  	
		document.getElementById("Name").addEventListener("keypress", liveSearchKeyPress, false);
		
	} else {
  	
		document.getElementById("Name").attachEvent("onkeydown", liveSearchKeyPress);
		isIE = true;
	}
}

function liveSearchKeyPress(event) { 
	
	//KEY DOWN
	if (event.keyCode == 40 )	{
  	
    highlight = document.getElementById("LSHighlight");
    
    if (!highlight) {
    	highlight = document.getElementById("topics").firstChild;
    } else {
    	highlight.removeAttribute("id");
    	highlight = highlight.nextSibling;
    }
    
    if (highlight) {
    	highlight.setAttribute("id","LSHighlight");
    }
    
    if (!isIE) { event.preventDefault(); }
	}
	
	//KEY UP
	else if (event.keyCode == 38 ) {
  	
    highlight = document.getElementById("LSHighlight");
    
    if (!highlight) {
    	highlight = document.getElementById("topics").lastChild;
    }
    else {
    	highlight.removeAttribute("id");
    	highlight = highlight.previousSibling;
    }
    
    if (highlight) {
    		highlight.setAttribute("id","LSHighlight");
    }
    
    if (!isIE) { event.preventDefault(); }
	}
	
	//ESC
	else if (event.keyCode == 27) {  	
		document.getElementById("topics").style.display = 'none';
	}
	else {
  		checksearch(document.getElementById('Search'));
	}
}

function checksearch(thisForm) {
	
	thisForm.action = liveSearchSubmit(thisForm);
	
	reloadMenu = true;
	preLoad(reloadMenu);
}

function liveSearchSubmit(thisForm) {
  
	var highlight = document.getElementById("LSHighlight");
	
	if (highlight) {  	
		return highlight.getAttribute("href");
	} 
	else {
		return "/alazanto4/index.php?s=" + thisForm.Name.value;
	}
}

function preLoad(reloadMenu) {
  
  if ((document.getElementById("Name").value != changeLast) || (reloadMenu == true)) { 
     
    if(win) {
      window.clearTimeout(win);
    }    
    win = setTimeout("loadXMLDoc('/alazanto4/livesearch.php')", 300);
  }
}

function loadXMLDoc(url) {
  
	document.getElementById("loader").src = "/alazanto4/Throbber-small.gif";
	
	clearTopicList();
	
	req = false;
	
  // branch for native XMLHttpRequest object
  if(window.XMLHttpRequest) {
  	try {
		req = new XMLHttpRequest();
      } catch(e) {
		req = false;
      }
      
  // 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;
      	}
	}
  }
    
  var searchedText = document.getElementById("Name").value;
	var searchedTextL = "?q=" + searchedText.toLowerCase();
	
	changeLast = document.getElementById("Name").value;
  
	if(searchedTextL != "?q=") {
	  	if(req) {
	  		req.onreadystatechange = processReqChange;
	  		req.open("POST", url + searchedTextL, true);
	  		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	  		liveSearchlast = searchedText;
	  		req.send(searchedTextL);
	  	}
	} else {
  	document.getElementById("loader").src = "/alazanto4/Throbber-small.png";
  	req.abort();
	}
}

// handle onreadystatechange event of req object

function processReqChange() {
	
    // only if req shows "loaded"
    if (req.readyState == 4) {
	    
        // only if "OK"
        if (req.status == 200) {
            buildTopicList();
         } else {
	        document.getElementById("loader").src = "/alazanto4/Throbber-small.png";
            alert("There was a problem retrieving the XML data:\n" +  req.statusText);            
         }
    }
}

// retrieve text of an XML document element, including elements using namespaces

function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    
    if (prefix && isIE) {
	    
      // IE/Windows
      result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
	    
	    // Safari/Mozilla
      result = parentElem.getElementsByTagName(local)[index];
    }
    
    if (result) {
	    
      // get text, accounting for possible whitespace (carriage return) text nodes 
      
      if (result.childNodes.length > 1) {
          return result.childNodes[1].nodeValue;
      } else {
          return result.firstChild.nodeValue;    		
      }
    } else {
        return "n/a";
    }
}

// fill Topics select list with items from the current XML document

function buildTopicList() {
	
  var divTopics = document.getElementById("topics");    	
  var items = req.responseXML.getElementsByTagName("item");
    
  // loop through <item> elements, and add each nested <name> <link> and <picture> element to Topics div_topics element
  
  if (document.getElementById("Search").value != "") {
    
	   	divTopics.style.display = "block";
	   	
	   	if (items.length == 0) {
		   	
		   	var nodeError = document.createTextNode("No Search Results");        
		    var paraObj = document.createElement("p");
		    
		    paraObj.appendChild(nodeError);		    
		    divTopics.appendChild(paraObj);
	   	} else {
		   		    
		    for (var i = 0; i < items.length; i++) {
			    	    
				var currentTitle = getElementTextNS("", "title", items[i], 0)
				var currentLink = getElementTextNS("", "permalink", items[i], 0)
	
		    appendToSelect(divTopics, currentTitle, currentLink);
	    }
    }
  }
	
  document.getElementById("loader").src = "/alazanto4/Throbber-small.png";
}

// empty Topics select list content

function clearTopicList() {	
	document.getElementById("topics").style.display = "none";
	
	var divTopics = document.getElementById("topics");
	var divTopicsClone = divTopics.cloneNode(false);
	
	document.getElementById("Search").removeChild(divTopics);
	document.getElementById("Search").appendChild(divTopicsClone);
}

// add item to select element the less elegant, but compatible way.

function appendToSelect(divTopics, currentTitle, currentLink) {
  
    highlight = document.getElementById("LSHighlight");  
    
    var nodeTitle = document.createTextNode(currentTitle);
        
    var anchorObj = document.createElement("a");
    anchorObj.appendChild(nodeTitle);
    anchorObj.href = currentLink;
    
    anchorObj.onmouseover = function() {
      
      if(highlight) {
        highlight.removeAttribute("id");
      }
       
      anchorObj.setAttribute("id","LSHighlight");
    }		
	anchorObj.onmouseout = function() { 
  		
  		anchorObj.removeAttribute("id");
  	}	
    
    divTopics.appendChild(anchorObj);
}

// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela

var Fat = {
	make_hex : function (r,g,b) 
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function ()
	{
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to) 
	{
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#ceeafc";
		if (!to) to = this.get_bgcolor(id);
		
		var frames = Math.round(fps * (duration / 200));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;
		
		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);
		
		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);
		
		var r,g,b,h;
		while (frame < frames)
		{
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);
		
			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame; 
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}

window.onload = function() {
	Fat.fade_all();
	liveSearchInit();
}