/*
// +----------------------------------------------------------------------+
// | Copyright (c) 2006 Dynamix Solutions                                 |
// +----------------------------------------------------------------------+
// | 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 + Upgraded and changed Dynamix Solutions        |
// +----------------------------------------------------------------------+
*/

//-----------------------------------------------------------------------
//Include Live search css
//-----------------------------------------------------------------------
document.write('<link type="text/css" href="/livesearch/livesearch.css" rel="stylesheet" media="screen" />');

//-----------------------------------------------------------------------
// Livesearch Variables
//-----------------------------------------------------------------------
var liveSearchReq = false;
var ajaxReq = false;
var t = null;
var liveSearchLast = "";
var liveSearchRoot = '/livesearch/';
var frm = null;
var fld = null;
var action = null;
var div_result = null;
var div_highlight = null;
var div_shadow = null;
  
var isIE = false;

// Preform search only when more than X characters entered
var minChars = 3;

//********************************************************
// @Function liveSearchInit 
// @Param fieldname: form fieldname  
// @Param _action: which action
// ==> 1 = Selected value in form field 
// ==> 2 = Selected value in form field + submit form
// ==> 3 = Selected value is URL and redirects to url
//********************************************************
function liveSearchInit(fieldname, _action) {
  // GET FIELD
  fld = document.getElementById(fieldname);
  if (!fld) return;

  div_result = fld.getAttribute('id') + "_result"
  div_highlight = "LSHighlight"
  div_shadow = fld.getAttribute('id') + "_shadow"
  frm = getForm(fld);
    
  toggleLoading(false);
  
  if (!action) {
    action = 1; 
  } else {
    action = _action;
  }

  if (navigator.userAgent.indexOf("Safari") > 0) {
    fld.addEventListener("keydown", liveSearchKeyPress, false);
    fld.addEventListener("blur", liveSearchHideDelayed, false);
  } else if (navigator.product == "Gecko") {
    fld.addEventListener("keypress", liveSearchKeyPress, false);
    fld.addEventListener("blur", liveSearchHideDelayed, false);
  } else {
    fld.detachEvent('onkeydown', liveSearchKeyPress);
    fld.attachEvent('onkeydown', liveSearchKeyPress);
    fld.detachEvent("onblur", liveSearchHideDelayed);
    fld.attachEvent("onblur", liveSearchHideDelayed);
    isIE = true;
  }
  
  fld.setAttribute("autocomplete","off");
}

function submitCancel() {
  return false;
}

//********************************************************
// @Function liveSearchHideDelayed 
// ==> hides the result div with a delay of 400 microsecs 
//********************************************************
function liveSearchHideDelayed() {
  window.setTimeout("liveSearchHide()",400);
}

//********************************************************
// @Function liveSearchHide 
// ==> hides the result div 
//********************************************************
function liveSearchHide() {
  document.getElementById(div_result).style.display = "none";
  var highlight = document.getElementById(div_highlight);
  if (highlight) {
    highlight.removeAttribute("id");
  }
}

//********************************************************
// @Function selectResult 
// @Param el: element  
// ==> highlights on mouse over
//********************************************************
function selectResult(el) {
  if (el) {
    highlight = document.getElementById(div_highlight);
    if (highlight) {
      highlight.removeAttribute("id");
    }
    
    el.setAttribute("id",div_highlight);
  } else {
    return false;
  }
  return true;
}

//********************************************************
// @Function liveSearchKeyPress 
// @Param event: key events gets captured
//********************************************************
function liveSearchKeyPress(event) {
  if ((event.ctrlKey || event.altKey || event.shiftKey) && event.keyCode >= 16 && event.keyCode <= 18) return;
  
  if (event.keyCode == 40 )
  //KEY DOWN
  {
    highlight = document.getElementById(div_highlight);
    if (!highlight) {
      highlight = document.getElementById(div_shadow).firstChild.firstChild;
    } else {
      highlight.removeAttribute("id");
      highlight = highlight.nextSibling;
    }
    if (highlight) {
      highlight.setAttribute("id",div_highlight);
    } 
    
    cancelEvent(event);
  } 
  //KEY UP
  else if (event.keyCode == 38 ) {  
    highlight = document.getElementById(div_highlight);
    if (!highlight) {
      highlight = document.getElementById(div_result).firstChild.firstChild;
      //highlight = document.getElementById(div_result).firstChild.firstChild.lastChild;
    } 
    else {
      highlight.removeAttribute("id");
      highlight = highlight.previousSibling;
    }
    if (highlight) {
        highlight.setAttribute("id",div_highlight);
    }

    cancelEvent(event);
  } 
  //ESC
  else if (event.keyCode == 27) {
    highlight = document.getElementById(div_highlight);
    if (highlight) {
      highlight.removeAttribute("id");
    }
    document.getElementById(div_result).style.display = "none";
  }
  //BACKSPACE - required for IE
  else if (event.keyCode == 8) {// && isIE) {
    //alert(fld.getAttribute('id'));
    liveSearchHideDelayed();
    //liveSearchStart();
  }
  // ENTER
  else if (event.keyCode == 13) {
    liveSearchSubmit();
    liveSearchHideDelayed();
    cancelEvent(event);
  }
  // TAB
  else if (event.keyCode == 9) {
    // CANCEL SEARCH
    liveSearchHide();
    if (liveSearchReq) {
      liveSearchReq.abort();
    }
  }
  // START SEARCHING
  else 
  {
    if (fld) {
      // Preform search only when minChars is reached
      if (fld.value.length >= minChars - 1) {
        liveSearchStart();
      } else {
        liveSearchHide();
      }
    }
  }
}

function cancelEvent(e) {
  if (isIE) {
    e.returnValue = false;
    e.cancelBubble = true;
  } else {
    e.preventDefault();
  }
}

//********************************************************
// @Function liveSearchStart 
// ==> with a timer start liveSearchDoSearch
//********************************************************
function liveSearchStart() {
  if (t) {
    window.clearTimeout(t);
  }
  t = window.setTimeout("liveSearchDoSearch()",200);
}

//********************************************************
// @Function liveSearchDoSearch 
// ==> get results from search_ .php file
//********************************************************
function liveSearchDoSearch() {

  if (typeof liveSearchRoot == "undefined") {
    liveSearchRoot = "";
  }
  
  if (typeof liveSearchRootSubDir == "undefined") {
    liveSearchRootSubDir = "";
  }
  
  if (typeof liveSearchParams == "undefined") {
    liveSearchParams2 = "";
  } else {
    liveSearchParams2 = "&" + liveSearchParams;
  }
  
  //if (liveSearchLast != fld.value) {
    if (liveSearchReq && liveSearchReq.readyState < 4) {
      liveSearchReq.abort();
    }
    if ( fld.value == "") {
      liveSearchHide();
      liveSearchLast = "";
      return false;
    }
    
    if (window.XMLHttpRequest) {
      liveSearchReq = new XMLHttpRequest();
    } else if (window.AciveXObject) {
      liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
      liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    toggleLoading(true);
  
    liveSearchReq.onreadystatechange= liveSearchProcessReqChange;
    liveSearchReq.open("GET", liveSearchRoot + "search_" + fld.getAttribute('name') + ".php?" + fld.getAttribute('name') +"=" + fld.value + liveSearchParams2, true);
    liveSearchLast = fld.value;
    liveSearchReq.send(null);
  //}
  
  return true;
}

//********************************************************
// @Function liveSearchProcessReqChange 
// ==> while getting data show image
//********************************************************
function liveSearchProcessReqChange() {
  if (liveSearchReq.readyState == 4) {
    toggleLoading(false);

    var pos = findPos(fld);
    var res = document.getElementById(fld.getAttribute('id') + "_result");
    var sh = document.getElementById(fld.getAttribute('id') + "_shadow");
    
    //res.style.left = pos[0];
    //res.style.top = pos[1] + 18;
    res.style.display = "block";
    //if (isIE)
    //{
    //  res.style.height = 0;
    //}
    
    sh.innerHTML = liveSearchReq.responseText;
    if (isIE)
    {
      window.setTimeout("getHeight()",200);
    }
  }
}

//********************************************************
// @Function toggleLoading 
// ==> show image or not
//********************************************************
function toggleLoading(value) {
  var el = document.getElementById(fld.getAttribute('name') + '_loading');
  if (el) {
    if (!value) {
      // HIDE LOADING IMAGE
      el.style.display = 'none';
    } else {
      // SHOW LOADING IMAGE
      el.style.display = '';
    }
  }
}

//********************************************************
// @Function liveSearchSubmit 
// ==> final action
//********************************************************
function liveSearchSubmit(_action) {
  var highlight = document.getElementById(div_highlight);
  
  var oldact = action;
  if (_action) {
    action = _action;
  }
    
  if (highlight && highlight.firstChild) {
    if (action == 1) {
      // VALUE IS VALUE
      // >> FILL IN FIELD
      // >> NO FORM SUBMIT
      //fld.value = highlight.firstChild.nextSibling.textContent;
      fld.value = highlight.firstChild.nextSibling.innerHTML.replace('&amp;', '&');
      action = oldact;
      return true;
    } else if (action == 2) {
      // VALUE IS VALUE
      // SUBMIT FORM WITH VALUE
      fld.value = highlight.firstChild.innerHTML.replace('&amp;', '&');
      submitForm();
      action = oldact;
      return false;
    } else if (action == 3) {
      // VALUE IS URL
      // >> OPEN
      window.location = highlight.firstChild.innerHTML.replace('&amp;', '&');
      action = oldact;
      return true;
    } else if (action == 4) {
      // VALUE IS VALUE
      // >> FILL IN FIELD
      // >> FORM SUBMIT
      fld.value = highlight.firstChild.nextSibling.innerHTML.replace('&amp;', '&');      
      submitForm();
      action = oldact;
      return false;
    } else if (action == 5) {
    }

    liveSearchHide();
  } else {
    if (action == 2 || action == 3 || action == 4) {
      // SUBMIT FORM WITH VALUE
      submitForm();
    }
  }
  
  action = oldact;
  return false;
}

//********************************************************
// @Function submitForm 
// ==> submits the complete form
//********************************************************
function submitForm(formname) {
  if (formname) {
    frm = document.getElementById(formname);
  } else {
    frm = getForm(fld);
  }
  
  // SUBMIT FORM
  frm.submit();
  return true;
}

function getForm(input_field) {
  var f = input_field.parentNode;
  while (f.tagName != 'FORM') {
    if (f.parentNode) {
      f = f.parentNode;
    } else {
      return null;
    }
  }
  return f;
}

function setPosition() {
  pos = findPos(fld);
}

function getHeight() {
    var ress = document.getElementById(fld.getAttribute('id') + "_result");
    var sha  = document.getElementById(fld.getAttribute('id') + "_shadow");
    var maxHeight = 200;
    var divHeight = 0;
    divHeight = sha.offsetHeight;
    if (divHeight > maxHeight)
    {
      ress.style.height = maxHeight;
    } else {
      if (isIE) {
        ress.style.height = divHeight + 10;
      } else {
      ress.style.height = divHeight;
      }
    }
}

/********************************************************
 * @Function findPos 
 * ==> finds the position of a object
 ********************************************************/
function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return [curleft,curtop];
}
