/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function Vorschlager(oTextbox /*:HTMLInputElement*/,
                     oTextbox2 /*:HTMLInputElement*/,
                     sArtSelector /*:HTMLInputElement*/,
                     oProvider /*:SuggestionProvider*/,
                     oBoxColorVar)
{
  /**
   * The currently selected suggestions.
   * @scope private
   */
  this.cur_num /*:int*/ = -1;
  this.highlighted_elem = null;
  this.has_focus = false;

  this.timeoutref = null;

  this.discardresultbeforenum = 0;

  if (oBoxColorVar)
    this.boxColorVar = oBoxColorVar;
  else
    this.boxColorVar = '';

  if (this.boxColorVar != '')
    this.activity_indicator_url = '/images/ajax/activity_indicator_weiss.gif';
  else
    this.activity_indicator_url = '/images/ajax/activity_indicator.gif';

  /**
   * The dropdown list layer.
   * @scope private
   */
  this.layer = null;
  this.layerdata = null;
  this.layerstatus = null;

  this.aSuggestions = Array();

  /**
   * Suggestion provider for the autosuggest feature.
   * @scope private.
   */
  this.provider /*:SuggestionProvider*/ = oProvider;

  /**
   * The textbox to capture.
   * @scope private
   */
  this.textbox /*:HTMLInputElement*/ = oTextbox;
  this.textbox2 /*:HTMLInputElement*/ = oTextbox2;

  this.art_selector = sArtSelector;

  this.emptybydefault = this.textbox.value == '';

  this.defaultvalue = this.textbox.title;

  this.isdefault = this.emptybydefault;

//  if (this.emptybydefault)
  {

    //this.isdefault = true;
    //this.defaultvalue = '';

    if (this.emptybydefault && this.defaultvalue != '')
      this.textbox.value = this.defaultvalue;
  }
  //initialize the control
  this.init();

}

Vorschlager.prototype.Update = function (new_value)
{
  if (this.isdefault)
  {
    this.defaultvalue = this.textbox.value;
  }
  this.isdefault = false;
  this.textbox.value = new_value;
};


Vorschlager.prototype.Reset = function ()
{
  this.cur_num = -1;
  this.highlighted_elem = null;
  this.aSuggestions = Array();
};

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */

Vorschlager.prototype.autosuggest = function (Suggestions, resultnum)
{
  if (!this.has_focus)
    return;
  if (resultnum < this.discardresultbeforenum)
    return;

  this.Reset();

  if (Suggestions == null)
    return;

  this.aSuggestions = Suggestions;


  //make sure there's at least one suggestion
  if (this.aSuggestions.length > 0)
  {
/*    if (this.aSuggestions.length > 15)
      this.SetMessage('Zuviele Ergebnisse.', true);
    else*/
      this.showSuggestions();
  } else
  {
    this.SetMessage('Keine Ergebnisse gefunden');
    //this.hideSuggestions();
  }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
Vorschlager.prototype.createDropDown = function ()
{

    var oThis = this;

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "vorschlaege" + this.boxColorVar;
    //this.layer.style.visibility = "hidden";
    this.layer.style.display = "none";

    this.layer.style.width = 'auto'; // '200px'

    this.layerstatus = document.createElement("span");
    this.layer.appendChild(this.layerstatus);

    this.layerdata = document.createElement("ul");
    this.layer.appendChild(this.layerdata);

    //Event.observe(window, 'resize', function() { oThis.hideSuggestions(); });
    $(window).bind('resize', function() { oThis.hideSuggestions(); });

    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox

    this.layerdata.onmousedown =
    this.layerdata.onmouseup =
    this.layerdata.onmouseover = function (oEvent)
    {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        
        if (oTarget.tagName != 'LI')
          return;

        if (oEvent.type == "mousedown")
        {
          //alert(this.aSuggestions); 
          //alert(oThis.aSuggestions); 
          //opera.debug(oThis);
          oThis.AdoptSuggestion(oTarget.getAttribute('id').split('_')[2])

          //oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover")
        {
          //if (oTarget.tagName == 'LI')
            oThis.highlightSuggestion(oTarget);
        } else
        {
            oThis.textbox.focus();
        }
    };

   document.body.appendChild(this.layer);
//   $$('div.page')[0].appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
Vorschlager.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;

    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }
  //  iLeft += this.textbox.offsetWidth + 4;
    return iLeft;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
Vorschlager.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;

    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
//    iTop -= (this.textbox.offsetHeight);

    return iTop;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
Vorschlager.prototype.handleKeyDown = function (oEvent /*:Event*/)
{
//  if (this.layer.style.visibility == 'visible')
  if (this.layer.style.display == 'block')

  switch(oEvent.keyCode)
  {
    case 38: //up arrow
      this.previousSuggestion();
      return false;
      break;
    case 40: //down arrow
      this.nextSuggestion();
      return false;
      break;
    case 13: //enter
      this.hideSuggestions();
      return false;
      break;
  }

};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
Vorschlager.prototype.handleKeyUp = function (oEvent /*:Event*/)
{
  if (this.textbox.value.length < 5)
  {
    this.hideSuggestions();
    return;
  } else
  {
    //this.SetNonResultText('Suche...', true);
  }

  var iKeyCode = oEvent.keyCode;

  if ((iKeyCode == 8 || iKeyCode == 46) || !(iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)))
  {
    if (this.timeoutref)
      window.clearTimeout(this.timeoutref);
    var oThis = this;
    this.timeoutref = window.setTimeout(function () { oThis.SendRequest(); }, 750);

  }
};

Vorschlager.prototype.SendRequest = function ()
{
  if (!this.has_focus)
    return;
  if (this.provider.requestSuggestions(this))
    this.SetWait('Suche...', true);
}


Vorschlager.prototype.SetMessage = function (text, show)
{
  var status = this.layerstatus
  status.innerHTML = "";  //clear contents of the layer

  status.style.width = '150px';
  status.appendChild(document.createTextNode(' ' + text));

  status.style.display = "block";

  this.layerdata.style.display = "none";

  if (show)
    this.Show();
};

Vorschlager.prototype.SetWait = function (text, show)
{
  var status = this.layerstatus
  status.innerHTML = "";  //clear contents of the layer

  var img = document.createElement("img");
  img.style.verticalAlign = 'middle';
  img.src = this.activity_indicator_url;
  status.appendChild(img);

  status.appendChild(document.createTextNode(' ' + text));

  status.style.display = "block";

  this.layerdata.style.display = "none";

  if (show)
    this.Show();
}

/* Blub */

Vorschlager.prototype.AdoptCurrentSuggestion = function ()
{
  if (this.aSuggestions != null && this.aSuggestions.length > 0)
  {
//  alert('Länge ' + this.aSuggestions.length);
//  alert(this.aSuggestions[this.cur_num]['name']);
    this.textbox.value = this.aSuggestions[this.cur_num]['name'];
    if (this.textbox2)
      this.textbox2.value = this.aSuggestions[this.cur_num]['region'];
  }
};

Vorschlager.prototype.AdoptSuggestion = function (suggestionnum)
{
  this.cur_num = parseInt(suggestionnum);
  this.AdoptCurrentSuggestion();
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
Vorschlager.prototype.hideSuggestions = function ()
{
//  this.layer.style.visibility = "hidden";
  this.layer.style.display = "none";

  this.Reset();
};

Vorschlager.prototype.highlightSuggestionNum = function (suggestionnum)
{
  //alert(this.textbox.name +'_item_'+suggestionnum);
  this.highlightSuggestion($('li#'+ this.textbox.name +'_item_'+suggestionnum)[0]);
  //window.status = suggestionnum;
}

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
Vorschlager.prototype.highlightSuggestion = function (new_cur_elem)
{
  if (new_cur_elem == null) // || new_cur_elem.getAttribute('id') === 'dummy')
  {
    return false;
  }

  if (this.highlighted_elem != null && this.highlighted_elem != new_cur_elem)
  {
      this.highlighted_elem.className = "";
  }

  this.highlighted_elem = new_cur_elem;
  this.highlighted_elem.className = "current";

  this.cur_num = parseInt(this.highlighted_elem.getAttribute('id').split('_')[2]);

  return true;

};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
Vorschlager.prototype.init = function ()
{
  // disable the browsers own autocomplete
//  this.textbox.setAttribute('autocomplete','off');

    //save a reference to this object
    var oThis = this;

    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {

        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }

        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };

    //assign onkeydown event handler
    this.textbox.onkeydown = function (oEvent) {

        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }

        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };

    //assign onblur event handler (hides suggestions)
    this.textbox.onblur = function ()
    {
      oThis.has_focus = false;
      oThis.hideSuggestions();
      if (oThis.textbox.value === '')
      {
        oThis.isdefault = true;
        oThis.textbox.value = oThis.defaultvalue;
      }
    };

    this.textbox.onfocus = function ()
    {
      oThis.has_focus = true;
      if (oThis.isdefault)
      {
        oThis.isdefault = false;
        //oThis.defaultvalue = oThis.textbox.value;
        oThis.textbox.value = '';

      }
    };

    //if (this.emptybydefault)
    {
      $(this.textbox.form).bind('submit',
        function ()
        {
          //alert('Moin');
          //oThis.textbox.setAttribute('autocomplete','on');
          if (oThis.isdefault)
          {
            oThis.textbox.value = '';
          }
        }
      );
    }

    //create the suggestions dropdown
    this.createDropDown();
};

/**
 * Highlights the next suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
Vorschlager.prototype.nextSuggestion = function ()
{
  this.highlightSuggestionNum(this.cur_num + 1)
  this.AdoptCurrentSuggestion();
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
Vorschlager.prototype.previousSuggestion = function ()
{
  this.highlightSuggestionNum(this.cur_num - 1);
  this.AdoptCurrentSuggestion();
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
Vorschlager.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange();
        oRange.moveStart("character", iStart);
        oRange.moveEnd("character", iLength - this.textbox.value.length);
        oRange.select();

    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }

    //set focus back to the textbox
    this.textbox.focus();
};

/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
Vorschlager.prototype.showSuggestions = function ()
{
  //if (this.aSuggestions === null)
  //  alert('NULL');

  var item = null;

  //this.layerstatus.style.visibility = "hidden";

  this.layerdata.innerHTML = "";  //clear contents of the layer

  //window.status = this.aSuggestions.length;

  for (var i=0; i < this.aSuggestions.length; i++)
  {
    item = document.createElement("li");
    item.setAttribute('id', this.textbox.name +'_item_'+i);
    //oDiv.value = i;
    item.appendChild(document.createTextNode(this.aSuggestions[i]['full']));
    this.layerdata.appendChild(item);
    //window.status += ' | ' + this.aSuggestions[i]['full'];
  }

  this.layerstatus.style.display = "none";
  this.layerdata.style.display = "block";

  this.Show();

};

Vorschlager.prototype.Show = function ()
{
  this.layer.style.left = (this.getLeft()+this.textbox.offsetWidth + 4) + "px";
  this.layer.style.top = (this.getTop()) + "px";
//  this.layer.style.visibility = "visible";
  this.layer.style.display = "block";

  
};
/**
 * Inserts a suggestion into the textbox, highlighting the
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
Vorschlager.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length;
        this.textbox.value = sSuggestion;
        this.selectRange(iLen, sSuggestion.length);
    }
};

function Vorschlaege(p1_default)
{
  this.remotedataurl = '/soap/dataproxy3.php';
  this.funcname = 'func=cn';
  this.lastfind;
  this.lastresult = Array();
  this.p1_default = p1_default;
  this.firstrun = true;
  this.requestcount = 0;

}

/**
 * Request suggestions for the given autosuggest control.
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
Vorschlaege.prototype.requestSuggestions = function (Vorschlager /*:AutoSuggestControl*/)
{
  //var find = Vorschlager.textbox.value.strip();
  var find = $.trim(Vorschlager.textbox.value);
  var find2 = $.trim(Vorschlager.textbox2.value);
  var sa = Vorschlager.art_selector != '' ? $(Vorschlager.art_selector).val() : this.p1_default;

  this.requestcount++;

  var oThis = this;


  var requestnum = this.requestcount;
  Vorschlager.discardresultbeforenum = requestnum;

  //window.status = 'finde ' + find;
  if (!this.firstrun)
  {
    //if (this.lastfind === find)
    if (this.lastresult[sa + find + find2])
    {
      Vorschlager.autosuggest(this.lastresult[sa + find + find2], requestnum);
      return;
    }
    //this.lastfind = find;

    if (this.myAjax)
    {
      this.myAjax.transport.abort();
      delete this.myAjax;
    }
  } else
  {
    this.firstrun = false;
    this.lastfind = find;
  }

  var pars = this.funcname;
  pars += '&p1=' + sa;
  pars += '&p2=' + encodeURIComponent(find);
  pars += '&p3=' + encodeURIComponent(find2);
  pars += '&nc=' + Math.random();

  $.ajax({
    type:'GET',
    url: this.remotedataurl+'?'+pars,
    dataType: 'json',
    success: function(data)
             {
               oThis.lastresult[sa + find + find2] = data;//eval(response)
               Vorschlager.autosuggest(oThis.lastresult[sa + find + find2], requestnum);
             },
    error: function (request) { Vorschlager.SetMessage(request.responseText); }
  });


/*
  this.myAjax = new Ajax.Request(this.remotedataurl,
    {
      method: 'get',
      parameters: pars,
      onComplete: function (originalRequest)
                  {
                    alert(originalRequest.status);
                    //if (this.responseIsSuccess)
                    {
                      var response = originalRequest.responseText;
                      if (response != '')
                      {

                        oThis.lastresult[sa + find] = eval(response)
                        Vorschlager.autosuggest(oThis.lastresult[sa + find]);
                      }
                    }
                  },
      onFailure: function (request) { Vorschlager.SetMessage('Keine Ergebnisse gefunden.'); }
    });*/

  return true;
};

function SetupVorschlager()
{
  VorschlagerInstanzen = {};
  if ($('.enableajax').length > 0)
  {
    var boxvar = '';
    if ($('table.persfahrform').length > 0 || $('div start').length > 0)
      boxvar = '2';

    var name = $('#start')[0];
    var ort = $('#startort')[0];
    var art = $('#startart')[0];
    if (name && ort)
      VorschlagerInstanzen['start'] = new Vorschlager(name, ort, 'input[name=sa]:checked', new Vorschlaege(0), boxvar);

    name = $('#ziel')[0];
    ort = $('#zielort')[0];
    if (name && ort)
      VorschlagerInstanzen['ziel'] = new Vorschlager(name, ort, 'input[name=za]:checked', new Vorschlaege(0), boxvar);

    if ($('#via').length > 0)
      VorschlagerInstanzen['via'] = new Vorschlager($('#via')[0], null, null, new Vorschlaege(0), 3);
      
  }
  if ($('#lgv').length > 0)
    VorschlagerInstanzen['lgv'] = new Vorschlager($('#lgv')[0], $('input#o')[0], null, new Vorschlaege(1), 2);      
  
}

  try
  {
    $(document).ready(SetupVorschlager);
  }
  catch(e)
  {
  }
