/*
	This is the JavaScript file for the AJAX Suggest Tutorial

	You may use this code in your own projects as long as this
	copyright is left	in place.  All code is provided AS-IS.
	This code is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

	For the rest of the code visit http://www.DynamicAJAX.com

	Copyright 2006 Ryan Smith / 345 Technical / 345 Group.

        Modified by Morten Hustveit <morten@rashbox.org> 2008 for stay.com
*/

function showMap()
{
  e('mapLink').style.display = 'none';
  e('map').style.display = 'block';
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject('Microsoft.XMLHTTP');
	} else {
                return null;
	}
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
var suggestCache = new Array();
var suggestString, suggestFocus, suggestCount;
var lastSuggest = '';
var suggestMode = 'normal';

function e(id) { return document.getElementById(id); }

function setFocus(index)
{
  if(index == suggestFocus)
    return;

  if(suggestFocus != -1)
  {
    el = e('suggestion_' + suggestFocus);
    if(el && el.className)
      el.className = 'suggest_link';
  }

  el = e('suggestion_' + index);
  if(el && el.className)
  {
    el.className = 'suggest_link_focus';
  }

  suggestFocus = index;
}

function setDestination(d)
{
  e('destQuery').value = d;
  e('search_suggest').style.display = 'none';
}

function setResponseText(responseText)
{
  var ss = e('search_suggest');
  var si = e('suggest_items');
  var str = responseText.split("\n");
  var html = '';

  suggestFocus = -1;

  if(str.length <= 1)
  {
    ss.style.display = 'none';
    suggestCount = 0;
  }
  else
  {
    suggestCount = str.length - 1;
    first = true;

    for(i = 0; i < suggestCount; i++)
    {
      var tok = str[i].split('|');

      if(tok[1] >= 100)
        html += '<div id="suggestion_' + i + '" class="suggest_link"><b>';
      else
      {
        if(first && i != 0)
          html += '<div id="suggestion_' + i + '" class="suggest_link spacer">';
        else
          html += '<div id="suggestion_' + i + '" class="suggest_link">';
        first = false;
      }

      if(suggestMode == "normal")
        html += '<a href="' + tok[2] + '">' + tok[0] + '</a>'
      else
        html += '<a href=\'javascript:setDestination("' + escape(tok[0]) + '")\'>' + tok[0] + '</a>'

      if(tok[1] >= 100)
        html += '</b>';

      html += '</div>';
    }

    ss.style.left = getPageOffsetLeft(e('destQuery')) + 'px';
    ss.style.display = 'block';
  }

  si.innerHTML = html;
}

//Called from keyup on the search textbox.
//Starts the HTTP request.
function searchSuggest() {
    var str = e('destQuery').value.replace(/^\s+|\s+$/g, '');

    if(str == lastSuggest)
      return;

    if(e('map'))
    {
      e('map').style.display = 'none';
      e('mapLink').style.display = 'block';
    }

    lastSuggest = str;

    if (str == "")
        e('search_suggest').style.display = "none";
    else if (suggestCache[str])
        setResponseText(suggestCache[str]);
    else if (searchReq.readyState == 4 || searchReq.readyState == 0)
    {
        suggestString = str;
        searchReq.open("GET", '/suggest?q=' + escape(str) + '&mode=' + escape(suggestMode), true);
        searchReq.onreadystatechange = handleSearchSuggest;
        searchReq.send(null);
    }
}

function getPageOffsetLeft(el){var ol=el.offsetLeft;while((el=el.offsetParent) != null){ol += el.offsetLeft;}return ol;}

//Called when the HTTP response is returned.
function handleSearchSuggest()
{
  if (searchReq && searchReq.readyState == 4)
  {
    suggestCache[suggestString] = searchReq.responseText;
    setResponseText(searchReq.responseText);

    if(lastSuggest != suggestString)
    {
      suggestString = lastSuggest;
      searchReq.open("GET", '/suggest?q=' + escape(lastSuggest), true);
      searchReq.onreadystatechange = handleSearchSuggest;
      searchReq.send(null);
    }
  }
}

function keyDown(ev)
{
  if(!ev && window.event)
    ev = window.event;

  if(ev.target == e('destQuery'))
  {
    if(ev.keyCode == 38)
    {
      if(suggestFocus > 0)
        setFocus(suggestFocus - 1);
      else
        setFocus(suggestCount - 1);

      return false;
    }
    else if(ev.keyCode == 40)
    {
      if(suggestFocus + 1 < suggestCount)
        setFocus(suggestFocus + 1);
      else
        setFocus(0);

      return false;
    }
    else if(ev.keyCode == 13 || ev.keyCode == 3)
    {
      if(suggestFocus >= 0)
      {
        el = e('suggestion_' + suggestFocus);

        if(suggestMode == 'normal')
        {
          while(!el.href)
            el = el.firstChild;

          window.location = el.href;
        }
        else
        {
          while(!el.href)
            el = el.firstChild;

          setDestination(el.innerHTML);
        }

        return false;
      }
    }
  }

  return true;
}

function clickHandler(ev)
{
  if(!ev && window.event)
    ev = window.event;

  if(!e('search_suggest'))
    return true;

  if(ev.target != e('search_suggest'))
    e('search_suggest').style.display = 'none';

  return true;
}

function installSuggest()
{
  document.onkeypress = keyDown;
  document.onclick = clickHandler;
}
