/*
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: Bitflux GmbH <devel@bitflux.ch>                              |
// +----------------------------------------------------------------------+
*/

var liveSearchReq = false;
var t = false;
var liveSearchLast = "";    // for some reaon this is needed for the keyb shortcuts to work
var isIE = false;
var liveSearchType = '';
var doing_search = false;
var start_millis = 0;
var ls_obj = false;
var highlight = false;

// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
	liveSearchReq = new XMLHttpRequest();
}


function liveSearchInit(element) {
  if (navigator.userAgent.indexOf("Safari") > 0) {
    $(element).addEventListener("keydown",liveSearchKeyPress,false);
  }
  else if (navigator.product == "Gecko") {
    $(element).addEventListener("keypress",liveSearchKeyPress,false);
    //$(element).addEventListener("blur",liveSearchHideDelayed,false);
  }
  else {
    $(element).attachEvent('onkeydown',liveSearchKeyPress);
    isIE = true;
  }
  $(element).setAttribute("autocomplete","off");
}


function liveSearchHideDelayed() {
	window.setTimeout("liveSearchHide()",400);
}


function liveSearchHide() {
  var result = $("LSResult")
  if(result) {
    result.style.display = "none";
  }
	highlight = $("LSHighlight");
	if (highlight) {
	  highlight.removeAttribute("id");
	}
}


function liveSearchHideAlways() {
	$("LSResult").style.display = "none";
	highlight = $("LSHighlight");
	if (highlight) {
		highlight.removeAttribute("id");
	}
	document.cookie = 'liveSearchHideAlways=1; expires=Thu, 2 Aug 2020 20:47:11 UTC; path=/';
	liveSearchHide();
}


function liveSearchShowSuggestions() {
	document.cookie = 'liveSearchHideAlways=; expires=Thu, 2 Aug 1999 20:47:11 UTC; path=/';
	liveSearchLast = '';
  window.setTimeout("liveSearchDoSearch()",400);
}


// keyboard navigation
function liveSearchKeyPress(event) {
	//KEY DOWN
	if (event.keyCode == 40)	{
    highlight = $("LSHighlight");
    if (!highlight) {
      // highlight second item because the first is the 'choose suggestions' text
      //highlight = $("LSResult").firstChild.childNodes.item(1);
      //alert($("LSResult"));
    }
    else {
      // highlight 2nd to last item because last is some help text
      highlight.removeAttribute("id");
      highlight = highlight.nextSibling;
      if(highlight) {
 			  if(highlight.nodeType == 3) {
	        highlight = highlight.nextSibling;
			  }
			}
      if(highlight.id == 'LSHelp2') {
        highlight = highlight.nextSibling;
      }
    }
    if (highlight) {
      highlight.setAttribute("id","LSHighlight");
    }
    if (!isIE) {
      event.preventDefault();
    }
	} 

	//KEY UP
  else if (event.keyCode == 38 ) {
    highlight = $("LSHighlight");
    if (!highlight) {
      // highlight 2nd to last item because last is some help text
    } 
    else {
      highlight.removeAttribute("id");
      highlight = highlight.previousSibling;
      if(highlight) {
 			  if(highlight.nodeType == 3) {
	        highlight = highlight.previousSibling;
			  }
			}
      if(highlight.id == 'LSHelp1') {
        highlight = highlight.previousSibling;
      }
    }
    if (highlight) {
      highlight.setAttribute("id","LSHighlight");
    }
    if (!isIE) {
      event.preventDefault();
    }
  } 

  //ESC
  else if (event.keyCode == 27) {
    highlight = $("LSHighlight");
    if (highlight) {
      highlight.removeAttribute("id");
    }
    $("LSResult").style.display = "none";
  } 

  //BACKSPACE - required for IE
  else if (event.keyCode == 8 && isIE) {
    liveSearchStart(ls_obj, liveSearchType);
  }

	//ENTER
	if (event.keyCode == 13)	{
    if($("LSHighlight")) {
      highlight = $("LSHighlight").firstChild.getAttribute('name');
      ls_obj.value = highlight.replace('\\\'', '\'');
      liveSearchHide();
      return false;
    }
    else {
      liveSearchHide();
      return false;
    }
  }
  
}

function liveSearchLoading() {
  if($("LSResult_" + liveSearchType)) {
    var l = $("LSResult_" + liveSearchType);
  }
  else {
    var l = $("LSResult");
  }
  if(l.style.display != 'block' || !l.innerHTML.match(/loading\.gif/)) {
    if(!$("LSResult_" + liveSearchType)) {
      var pos = findPos(ls_obj);
      l.style.left = pos[0] +  'px';
      l.style.top = pos[1] + ls_obj.clientHeight + 2 + 'px';
    }
    l.innerHTML = "<div style=\"font-size: 11px; font-weight: bold; padding: 2px 0px 5px 0px;\"><table cellpadding=\"0\" cellspacing=\"0\" width=\"294\" border=\"0\"><tr><td width=\"24\"><img src=\"/img/loading.gif\" /></td><td>Finding suggestions...</td><td align=\"right\"><a href=\"javascript:liveSearchHideAlways();\" name=\"hide_link\" style=\"font-weight: normal;\">Hide</a></td></tr></table></div>";
    l.style.display = 'block';
  }  
}

function liveSearchStart(obj, type) {
  ls_obj = obj;
  liveSearchType = type;
  
	if (t) {
		window.clearTimeout(t);
	}

  if(liveSearchType == 'interactions') {
    $('search_error').style.display='none';
  }

  // need to cancel existing search if new one made before finished
  // (ie user types consecutive keys > 200ms apart, but before server gives response
  if(doing_search) {
    liveSearchReq.abort();
  }
  
  t = window.setTimeout("liveSearchDoSearch()",200);

}


function liveSearchDoSearch() {
  doing_search = true;
  var start_time = new Date();
  start_millis = start_time.getSeconds()*1000 + start_time.getMilliseconds();
  query = ls_obj.value;
  
  if (liveSearchLast != query) {
    if (liveSearchReq && liveSearchReq.readyState < 4) {
      liveSearchReq.abort();
    }
    if (query == "") {
      liveSearchHide();
      liveSearchLast = "";
      return false;
    }
    if (window.ActiveXObject) {
      liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    liveSearchReq.onreadystatechange = liveSearchProcessReqChange;
    liveSearchReq.open("GET", "/ls-" + liveSearchType + ".php?q=" + query, true);
    liveSearchLast = query;
    liveSearchReq.send(null);
    liveSearchTimer();
  }
}

function liveSearchTimer() {
  if(doing_search) {
    var now_time = new Date();
    var now_millis = now_time.getSeconds()*1000 + now_time.getMilliseconds();
    if( (now_millis - start_millis) > 500) {
      if(liveSearchLast) {
        liveSearchLoading();
      }
    }
    window.setTimeout("liveSearchTimer()",100);
  }
  
}

function liveSearchProcessReqChange() {
  if (liveSearchReq.readyState == 4) {
    if(liveSearchReq.responseText) {
      
      // need to support 'old, relative' method - some pages in ie7 dont work well with abs
      if($("LSResult_" + liveSearchType)) {
        var res = $("LSResult_" + liveSearchType);
      }
      else {
        var res = $("LSResult");
        var pos = findPos(ls_obj);
        res.style.left = pos[0] +  'px';
        res.style.top = pos[1] + ls_obj.clientHeight + 2 + 'px';
      }

      res.innerHTML = liveSearchReq.responseText;
      res.style.display = "block";
      
      doing_search = false;
    }
	}
}




function liveSearchSubmit() {
  return false;
}

