suggest = (function() {
    var self = this;
    self.type = "";
    self.func_name = "";
    self.timer = -1;
    self.callValue = null;
    self.cache = new Object();
    self.position = -1;
    self.enteredValue = null;
    self.parentBox = new Object();
    self.contentBox = new Object();
    self.scroller = new Object();
    self.isKeyUpDownPressed = true;
    self.suggestions = 0;
    self.waitingResponse = false;
    self.minVisiblePosition = 0;
    self.maxVisiblePosition = 9;

    self.deselectAll = function()
    {
      for(var i=0; i < self.suggestions; i++)
      {
        var oCrtTr = self.parentBox.find("#tr" + i);
        oCrtTr.removeClass("highlightrow");
      }
    }

    self.getDataFromServer = function() {
        $.ajax({
                url: self.func_name,
                type: 'POST',
                dataType: 'text',
                data: {
                    'id': self.callValue,
                    'task': 'suggest'
                },
                success: function (res) {
                    if(self.waitingResponse)
                    {
                        self.contentBox.html(res)
                            .parent()
                            .css({"visibility": "visible"});
			self.position = -1;
			self.minVisiblePosition = 0;
			self.maxVisiblePosition = 9;
			self.waitingResponse = false;
                    }
                    self.cache[self.callValue] = res;
                }
            })
            self.waitingResponse = true;
    }

    self.refreshResults = function(value) {
        if (value.length > 0) {
            var context = this;
            if(self.cache[value])
            {
                context.value = value;
                self.contentBox.html(self.cache[value])
                    .parent()
                    .css({"visibility": "visible"});
                self.position = -1;
                self.minVisiblePosition = 0;
                self.maxVisiblePosition = 9;
            }
            else
            {
                if(self.timer == -1)
                {
                    context = this;
                    self.callValue = value;
                    self.timer = setTimeout(self.getDataFromServer, 200)
                }
            }
        } else {
           self.scroller.css({"visibility":"hidden"});
        }

    }

    self.updateValue = function(){
        if(self.enteredValue == null)
            self.enteredValue = $("#" + self.type + "_keyword").val();
        if(self.position >= 0){
            $("#" + self.type + "_keyword").val(self.contentBox.find("#tr" + self.position).text());
        }
    }

    self.restoreValue = function(){
        if(self.enteredValue != null)
             $("#" + self.type + "_keyword").val(self.enteredValue);
         self.enteredValue = null;
    }

    return {
	initSuggest: function (type) {
            self.type = type;
            switch (type) {
                case "right":
                case "people": self.func_name = "/ajax_people_suggest.php";
                               break;
                case "single-venues":
                               self.func_name = "/venue/venues.php";
                               break;
                case "venues": self.func_name = "venues.php";
                               break;
            }
            self.enteredValue = null;
            self.parentBox = $("#" + self.type + "_keyword").parent();
            self.contentBox = $("#" + self.type + "_suggest");
            self.scroller = $("#" + self.type + "_scroll");
	},
        handleOnMouseOver:function(oTr){
          self.contentBox.find("#tr" + self.position).removeClass("highlightrow");
          oTr.addClass("highlightrow");
          self.position = parseInt(oTr.attr("id").substring(2, oTr.attr("id").length));
          self.updateValue();
        },
        handleOnMouseOut:function(oTr){
          oTr.removeClass("highlightrow");
          //self.position = -1;
        },
        onFocusSuggestIn:function(elem) {
            var id = $(elem).attr("id");
            suggest.initSuggest(id.substring(0, id.indexOf('_')));
            
            var value = $(elem).val();
            if((self.type == "venues" && value == 'Search By Name') || (self.type == "single-venues" && value == 'Find a place') || ((self.type == "people" || self.type == "right") && value == 'Find people in photos'))
                $('#' + self.type + '_keyword').val('')
                                               .css({
                                                   'color': '#000000',
                                                   'background-color': '#FFFFFF'
                                               });
            else
            {
                if (value.length > 0) {
                    $('#' + self.type + '_scroll').css({"visibility":"visible"});
                    self.restoreValue();
                }
            }
        },
        onFocusSuggestOut:function(value) {
            setTimeout(function(){self.scroller.css({"visibility":"hidden"})}, 100);
            //$('#' + self.type + '_keyword').val('');
        },
        goCurrent:function() {
            if(self.position >= 0)
            {
                location.href = self.parentBox.find("#a" + self.position).attr("href");
            }
        },
        handleSuggestKeyUp:function(e)
        {
          // get the event
          e = (!e) ? window.event : e;
          // get the event's target
          var target = (!e.target) ? e.srcElement : e.target;
          if (target.nodeType == 3)
            target = target.parentNode;
          // get the character code of the pressed button
          var code = (e.charCode) ? e.charCode :
               ((e.keyCode) ? e.keyCode :
               ((e.which) ? e.which : 0));
            // get the event
          e = (!e) ? window.event : e;
          // get the event's target
          target = (!e.target) ? e.srcElement : e.target;
          if (target.nodeType == 3)
            target = target.parentNode;
          // get the character code of the pressed button
          code = (e.charCode) ? e.charCode :
               ((e.keyCode) ? e.keyCode :
               ((e.which) ? e.which : 0));
          // check to see if the event was keyup
          if (e.type == "keyup")
          {
            isKeyUpDownPressed =false;
            // check to see we if are interested in the current character
            if ((code < 13 && code != 8) ||
                (code >=14 && code < 32) ||
                (code >= 33 && code <= 46 && code != 38 && code != 40) ||
                (code >= 112 && code <= 123))
            {
              // simply ignore non-interesting characters
            }
            else
            /* if Enter is pressed we jump to the PHP help page of the current
               function */
            if(code == 13)
            {
              // check to see if any function is currently selected
              if(self.position>=0)
              {
                this.goCurrent();
              }
            }
            else
            // if the down arrow is pressed we go to the next suggestion
              if(code == 40 && !self.scroller.is(':hidden'))
              {
                oldTR = self.parentBox.find("#tr" + (self.position));
                newTR = self.parentBox.find("#tr" + (self.position + 1));
                // deselect the old selected suggestion
                if(newTR.length == 1)
                {
                  oldTR.removeClass("highlightrow");
                  newTR.addClass("highlightrow");
                  self.position ++;
                  self.updateValue();
                }
                e.cancelBubble = true;
                e.returnValue = false;
                isKeyUpDownPressed = true;
                // scroll down if the current window is no longer valid
                if(self.position >= self.maxVisiblePosition)
                {
					self.maxVisiblePosition++;
					self.minVisiblePosition++;
                }
              }
              else
              // if the up arrow is pressed we go to the previous suggestion
              if(code == 38 && !self.scroller.is(':hidden'))
              {

                oldTR = self.parentBox.find("#tr"+(self.position));
                newTR = self.parentBox.find("#tr"+(self.position - 1));
                // deselect the old selected position

                if(newTR.length == 1)
                {
                  oldTR.removeClass("highlightrow");
                  newTR.addClass("highlightrow");
                  self.position --;
                  self.updateValue();

                }
                else
                {

					if(self.position == 0){
						self.position --;
						self.restoreValue();
						oldTR.removeClass("highlightrow");

					}
                }
                // scroll up if the current window is no longer valid
                if(self.position < self.minVisiblePosition)
                {
					self.maxVisiblePosition--;
					self.minVisiblePosition--;
                }

                e.cancelBubble = true;
                e.returnValue = false;
                isKeyUpDownPressed = true;
              } else {
                  clearTimeout(self.timer);
                  self.timer = -1;
                  self.refreshResults($('#' + self.type + '_keyword').val());
              }
          }
          else
          {
            if ((code <= 13 && code != 8) ||
                (code >=14 && code < 32) ||
                (code >= 33 && code <= 46) ||
                (code >= 112 && code <= 123))
            {
            }else
            {
                self.restoreValue();
                self.refreshResults($('#' + self.type + '_keyword').val());
            }
          }
      }
   }
})();
