// $Id: autocomplete.js,v 1.23 2008/01/04 11:53:21 goba Exp $

function wordwrap( str, int_width, str_break, cut ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Nick Callen
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // *     example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
    // *     returns 1: 'Kevin |van |Zonnev|eld'
    // *     example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br />\n');
    // *     returns 2: 'The quick brown fox <br />\njumped over the lazy<br />\n dog.'
    // *     example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.');
    // *     returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.'
 
    // PHP Defaults
    var m = ((arguments.length >= 2) ? arguments[1] : 75   );
    var b = ((arguments.length >= 3) ? arguments[2] : "\n" );
    var c = ((arguments.length >= 4) ? arguments[3] : false);
 
    var i, j, l, s, r;
 
    str += '';
 
    if (m < 1) {
        return str;
    }
 
    for (i = -1, l = (r = str.split("\n")).length; ++i < l; r[i] += s) {
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
        }
    }
 
    return r.join("\n");
}

/**
 * Attaches the autocomplete behavior to all required fields
 */
Drupal.behaviors.mmg_autocomplete = function (context) {
  var acdb = [];
  $('input.mmg_autocomplete:not(.autocomplete-processed)', context).each(function () {
    var uri = this.value;
    if (!acdb[uri]) {
      acdb[uri] = new Drupal.ACDB_mmg(uri);
    }    
    var input = $('#' + this.id.substr(0, this.id.length - 13))
      .attr('autocomplete', 'OFF')[0];
    $(input.form).submit(Drupal.autocompleteSubmit);
    new Drupal.jsAC_mmg(input, acdb[uri]);
    $(this).addClass('autocomplete-processed');
  });
  
  $('#edit-mmg-autocomplete-node-finder-keywords-0').focus(function()
    {
        //alert('on focus function');
        var sCurrentVal = $(this).attr('value');
        //alert('current text: '+sCurrentVal);
        $(this).attr('value', '');
    }
    );
    
    /*
    $('.form-autocomplete').blur(function()
    {
        //alert('on blur function');
        var sCurrentVal = $(this).attr('value');
        //alert('current text: '+sCurrentVal);
        if(sCurrentVal == '')
        {
            $(this).attr('value', 'search for places, ideas, information, business');
        }
    }
    );
    */
 
};

/**
 * Prevents the form from submitting if the suggestions popup is open
 * and closes the suggestions popup when doing so.
 */
Drupal.autocompleteSubmit = function () {
  return $('#autocomplete').each(function () {
    this.owner.hidePopup();
  }).size() == 0;
};

/**
 * An AutoComplete object
 */
Drupal.jsAC_mmg = function (input, db) {
  var ac = this;
  this.input = input;
  this.db = db;
  
  $(this.input)
    .keydown(function (event) { return ac.onkeydown(this, event); })
    .keyup(function (event) { ac.onkeyup(this, event); })
    .blur(function () { ac.hidePopup(); ac.db.cancel(); });
	
  var submitObj = document.getElementById('edit-mmg-autocomplete-node-finder-submit');
  $(submitObj).click(function (){ 
		if(ac.input.value != ''){
			ac.input.form.action = '/advanced-search';
			ac.input.form.submit();
		}
		return false;
	}
	);
	
   /*$(submitObj).css({
		top: this.input.offsetHeight +'px',
		left: findPosX(this.input) +'px'		
	  });*/  
};

/**
 * Handler for the "keydown" event
 */
Drupal.jsAC_mmg.prototype.onkeydown = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 40: // down arrow
      this.selectDown();
      return false;
    case 38: // up arrow
      this.selectUp();
      return false;
    case 39: // right arrow
    	this.selectRight();
    	return false;  		
    case 37: // left arrow 
    	this.selectLeft();   	   	
    	return false;  	
    default: // all other keys      
      return true;
  }
};

/**
 * Handler for the "keyup" event
 */
Drupal.jsAC_mmg.prototype.onkeyup = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
      return true;

    case 9:  // tab
    case 13: // enter
		if(this.selected.autocompleteValue){
			this.hidePopup(e.keyCode);
			return true;
		}
				
		input.form.action = '/advanced-search';
		input.form.submit();
	 	return true;
    case 27: // esc
      this.hidePopup(e.keyCode);
      return true;

    default: // all other keys
      if (input.value.length > 0)
        this.populatePopup();
      else
        this.hidePopup(e.keyCode);
      return true;
  }
};

/**
 * Puts the currently highlighted suggestion into the autocomplete field
 */
Drupal.jsAC_mmg.prototype.select = function (node) {
  //this.input.value = node.autocompleteValue;
  //alert(node.autocompleteValue);
};

/**
 * Highlights the next suggestion
 */
Drupal.jsAC_mmg.prototype.selectDown = function () {
  if (this.selected && this.selected.nextSibling) {
    this.highlight(this.selected.nextSibling);
  }
  else {
    var lis = $('li', this.popup);
    if (lis.size() > 0) {
      this.highlight(lis.get(0));
    }
  }
};

/**
 * Highlights the right suggestion
 */
Drupal.jsAC_mmg.prototype.selectRight = function () {

	var uis = $('ul', this.popup);
	if(uis.size()>0){
	    var lis = $('li', uis.get(1));
	    if (lis.size() > 0) {
	      this.highlight(lis.get(0));
	    }
	}
  
};

/**
 * Highlights the left suggestion
 */
Drupal.jsAC_mmg.prototype.selectLeft = function () {

	var uis = $('ul', this.popup);
	if(uis.size()>0){
	    var lis = $('li', uis.get(0));
	    if (lis.size() > 0) {
	      this.highlight(lis.get(0));
	    }
	}
  
};


/**
 * Highlights the previous suggestion
 */
Drupal.jsAC_mmg.prototype.selectUp = function () {
  if (this.selected && this.selected.previousSibling) {
    this.highlight(this.selected.previousSibling);
  }
};

/**
 * Highlights a suggestion
 */
Drupal.jsAC_mmg.prototype.highlight = function (node) {
  if (this.selected) {
    $(this.selected).removeClass('selected');
  }
  $(node).addClass('selected');
  this.selected = node;
};

/**
 * Unhighlights a suggestion
 */
Drupal.jsAC_mmg.prototype.unhighlight = function (node) {
  $(node).removeClass('selected');
  this.selected = false;
};

/**
 * Hides the autocomplete suggestions
 */
Drupal.jsAC_mmg.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    //this.input.value = this.selected.autocompleteValue;
	if(this.selected.autocompleteValue != 'undefined'){
		var key_value = this.selected.autocompleteValue.split("##");
		if(key_value[1])
		{
			this.input.value = key_value[0];
			document.location.href=key_value[2];
		}
		else
			document.location.href=this.selected.autocompleteValue;
	}else{		
		this.input.form.action = '/advanced-search';
		this.input.form.submit();
	}
  }
  // Hide popup
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function() { $(popup).remove(); });
  }
  this.selected = false;
};

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
/**
 * Positions the suggestions popup and starts a search
 */
Drupal.jsAC_mmg.prototype.populatePopup = function () {
  /*Commented following code so that the autocomplete search results box stays open whenever each key stroke is entered.22-01-2009*/
  // Show popup
  /*if (this.popup) {
    $(this.popup).remove();
  }*/
  this.selected = false;
  var divId = document.getElementById('autocomplete');
  /*Added 'if' condition to restrict creation of new div elements everytime new search results are gathered in the popup.22-01-2009*/
  if(divId==null){
	  this.popup = document.createElement('div');
	  this.popup.id = 'autocomplete';
	  this.popup.owner = this;
    //alert(findPosX(this.input));
	  /*$(this.popup).css({
		marginTop: (this.input.offsetHeight+5) +'px',
		width: (this.input.offsetWidth + 12) +'px',
    marginLeft: (-7) +'px',
    zIndex : 100000000,
    position:'absolute',
    left:'0px',
		//left: findPosX(this.input) +'px',
    //'z-index' : -9111,
		display: 'none'
	  });*/
    //$(this.popup).css('z-index','9999999');
	  $(this.input).before(this.popup);
  }
  // Do search
  this.db.owner = this;
  this.db.search(this.input.value);
};

/**
 * Fills the suggestion popup with any matches received
 */
Drupal.jsAC_mmg.prototype.found = function (matches)
{
	// If no value in the textfield, do not show the popup.
	if (!this.input.value.length) { return false; }
	
	var ac = this;
	
	// Prepare matches
	
	var div = document.createElement('div'); // #autocomplete
	var tbl = document.createElement('table');
	var tr = document.createElement('tr');
	
	$(div).attr('style', 'asddsda');
	$(tbl).attr('cellspacing', '0');
	
	var i = 1;
	var item1 = 0;
	var ccount = 0;
	
	for (var item_node in matches) { ccount++; }
	
	for (var item_node in matches)
	{
		var td = document.createElement('td');
		var div1 = document.createElement('div');  
		var ul = document.createElement('ul');
		var cnt = 1;
		var title_match = item_node.split("$$$");
		var link_match = title_match[2].split("'");
		var lih = document.createElement('li');
		
		$(lih).html('<span>' + title_match[1] + '</span>');
		$(ul).append(lih);
		
		if (matches[item_node] == '')
		{
			var li = document.createElement('li');
			var cntheight = 22 * ((title_match[2].length) / 20);
			
			if (ccount > 1) { $(li).html('<span>' + wordwrap(title_match[2], 30, '<br />', true) + '</span>'); }
			else { $(li).html('<span>'+title_match[2]+'</span>'); }
			$(li).attr("onclick", "document.location.href = '" + link_match[1] + "'");
			li.autocompleteValue = link_match[1];
			$(ul).append(li);
			
			cnt++;
		}
		else
		{
			for (key in matches[item_node])
			{
				cnt++;
				
				var li = document.createElement('li');
				var node_match = matches[item_node][key].split("###");
				
				$(li).html('<span>'+  wordwrap(node_match[0], 35, '<br />', true) +'</span>')
				     .mousedown(function () { ac.select(this); })
				     .mouseover(function () { ac.highlight(this); })
				     .mouseout(function () { ac.unhighlight(this); });
				li.autocompleteValue = node_match[0] + '##' + title_match[0] + '##' + node_match[1];
				$(ul).append(li);
			}
		}
		
		$(lih).addClass('heading');
		
		//if (ccount>1) { $(li).attr("style", "width:189px"); }
		
		if (i == 1)
		{
			var item1 = cnt;
			var height = cnt * 22;
		}
		else
		{
			if (item1 <= cnt) { var height = cnt * 22; }
			//$(td).attr("style", "background-color:#FFFFFF;vertical-align:top;width:50%;border-left:1px solid #000000;");
		}
		//$(ul).attr("style", "padding-left:6px;height:inherit;background-color:#FFFFFF;");
		//$(div1).attr("style", "top: 0px;width:100%;height:inherit;background-color:#FFFFFF;vertical-align:top;");
		
		i++;
		
		$(div1).append(ul);
		$(td).append(div1);
		$(tr).append(td);
		$(tbl).append(tr);
		$(div).append(tbl);
	}
	
	if (this.popup)
	{
		if (div.childNodes.length > 0) { $(this.popup).empty().append(div).show(); }
		else
		{
			$(this.popup).css({visibility: 'hidden'});
			this.hidePopup();
		}
	}
};

Drupal.jsAC_mmg.prototype.setStatus = function (status) {
   switch (status) {
    case 'begin':
      $(this.input).addClass('throbbing');
      break;
    case 'cancel':
    case 'error':
    case 'found':
      $(this.input).removeClass('throbbing');
      break;
  }
};

/**
 * An AutoComplete DataBase object
 */
Drupal.ACDB_mmg = function (uri) {
  this.uri = uri;
  this.delay = 300;
  this.cache = {};
};

/**
 * Performs a cached and delayed search
 */
Drupal.ACDB_mmg.prototype.search = function (searchString) {
  var db = this;
  this.searchString = searchString;

  // See if this key has been searched for before
  if (this.cache[searchString]) {
    return this.owner.found(this.cache[searchString]);
  }

  // Initiate delayed search
  if (this.timer) {
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(function() {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion
    $.ajax({
      type: "GET",
      url: db.uri +'/'+ Drupal.encodeURIComponent(searchString),
      dataType: 'json',
      success: function (matches) {
        if (typeof matches['status'] == 'undefined' || matches['status'] != 0) {
          db.cache[searchString] = matches;
          // Verify if these are still the matches the user wants to see
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        //alert(Drupal.ahahError(xmlhttp, db.uri));
      }
    });
  }, this.delay);
};

/**
 * Cancels the current autocomplete request
 */
Drupal.ACDB_mmg.prototype.cancel = function() {
  if (this.owner) this.owner.setStatus('cancel');
  if (this.timer) clearTimeout(this.timer);
  this.searchString = '';
};
