/**
 * Simple jQuery Plugin that allows to create an EquityStory Suggest feature.
 *
 * This relies on the search index that has to be created as shown in the Wiki
 * @see http://wiki.equitystory/index.php?title=Documentation_of_IR_Pages_2_Search_function#Search_function_for_Reports2_.26.26_Quick3
 *
 * Set up three includes for this plugin to work, for example:
 *
 * <script src="/hannoverre/annual/2009/gb/layout/js/jquery-1.4.1.min.js" type="text/javascript"></script>
 * <script src="/hannoverre/annual/2009/gb/layout/js/jquery.eqsuggest-0.1.js" type="text/javascript"></script>
 * <script src="/hannoverre/annual/2009/gb/German/js/suggestion.js" type="text/javascript"></script>
 *
 * Create the input element that the suggest feature should be attached, for example:
 *
 * <input type="text" id="search_input" value="Suche" name="search_keywords" />
 *
 * Last, the EQS Suggest feature has to be initialised when the page has loaded, for example:
 *
 * $(document).ready = function () {
 *    $('#search_input').eqsSuggest({
 *        'searchFormName' : 'searchForm',
 *        'hitLabel' : 'Treffer',
 *        'defaultKeys' : ['Aktie','Kurs','Verkauf'],
 *        'outputNodeID' : 'search'
 *    });
 * };
 *
 * The following configuration options can be passed in this initialisation:
 *
 *  - sizeID: The output of the suggest feature is put into a DIV object that
 *            usually takes position directly below the given input field and
 *            is at least as wide as the input field. To change this to a
 *            different element in the document, give the ID, e.g. "search"
 *  - resize: true if the output DIV object should be resized when the
 *            content requires more space, false if it should always keep the
 *            width of the input or size element (you have to deal with overflow
 *            yourself)
 *  - maxKeywords: Integer definition of how many elements should be suggested
 *  - searchFormName: name (not ID) of search form that should be submitted when
 *            a search term has been selected from a suggestion
 *  - hitLabel: Text displayed in the output stating "10 hitLabel"
 *  - hitBefore: Text before the hit count and label, default: (
 *  - hitAfter: Text after the hit count and label, default: )
 *  - defaultKeys: Array of keys that should be shown when the search input is
 *            focused, default: empty Array
 *  - padding: Integer with padding that you set on the output DIV element in your
 *             own CSS files. This is needed to calculate the width of the DIV
 *             browser independantly, default: 10
 *  - outputNodeID: If you need to have the output DIV appended to an already
 *             existing DOM element, give it's ID here - for example when you
 *             have a structured CSS file and do want the output in a specific
 *             container element, default: undefined
 *
 * @author Hendrik Bauer
 * @version 0.1
 *
 */

(function( $ ){
  $.fn.eqsSuggest = function(options) {
  
    var settings = {
	  'inputID'         : 'search_input',
	  'sizeID'          : 'search_input',
	  'resize'          : true,
      'maxKeywords'     : 10,
      'searchFormName'  : 'searchForm',
	  'hitLabel'        : 'Treffer',
	  'hitBefore'       : '(',
	  'hitAfter'        : ')',
	  'defaultKeys'     : [],
	  'padding'         : 10,
	  'outputNodeID'    : undefined
    };
	
	var methods = {
	  showOutput : function (output) {
		var pos = $('#'+settings.sizeID).position();
		var default_width = ($('#'+settings.sizeID).outerWidth() - (settings.padding*2));
		
		$('#search_output').css('width', default_width + "px").children().remove();
		$('#search_output').append(output);
		$('#search_output').slideDown();
		
		var qf = $('<div id="qf"></div>');
		if (settings.quickfinderID != '') {
			qf.appendTo($('#'+settings.outputNodeID+' #search_output'));
			var qfContent = $('#'+settings.quickfinderID).html();
			$('#qf').html(qfContent);
		}

		var current_width = $('#search_output table').outerWidth();
		var css = {
				  "left" : pos.left + "px",
				  "top"  : pos.top + $('#'+settings.sizeID).height() + "px",
				  "width": current_width > default_width ? (current_width + (settings.padding*2)) + "px" : default_width
		};
		$('#search_output').css(css);
	  },
	  setKeyword : function (key) {
		$('#' + settings.inputID).attr('value',key);
		$('#search_output').html = "";
		$('#search_output').css('display', "none");
		document.forms[settings.searchFormName].submit();
	  }
	}
	
	return this.each(function() {        
      if ( options ) { 
        $.extend( settings, options );
      }

	  settings.inputID = $(this).attr('id');
	  
	  var div = $('<div id="search_output"></div>');
	  div.css({
		'display':'none',
		'position':'absolute',
		'z-index':'1000',
		'float': 'left'
	  });
	  /*
	  div.css({
		'display':'none',
		'position':'absolute',
		'z-index':'1000'
	  });
	  */
	  if (settings.outputNodeID) {
		div.appendTo($('#'+settings.outputNodeID));
	  } else {
		div.appendTo(document.body);
	  }
	  
	  $(window).resize(function() {
		  var pos = $('#'+settings.sizeID).position();
		  var css = {
					  "left" : pos.left + "px",
					  "top"  : pos.top + ($(settings.sizeID).outerHeight()) + "px"
		  };
		  $('#search_output').css(css);
	  });
	    
	  $(this).focus(function() {
		$(this).val("");
		var output = "";
		var table  = $('<table />');
		if (settings.defaultKeys.length > 0) {
		  for(var i = 0; i < settings.defaultKeys.length; i++){
			  
			  var tr = $('<tr></tr>');
			  var td = $('<td class="keywordCol"></td>');
			  td.text(settings.defaultKeys[i]);
			  td.click(function() {
				methods.setKeyword($(this).text());
			  })
			  td.appendTo(tr);
			  tr.appendTo(table);
		  }
		  methods.showOutput(table);
		}
		var qf = $('<div id="qf"></div>');
		if (settings.quickfinderID != '') {
			qf.appendTo($('#'+settings.outputNodeID+' #search_output'));
			var qfContent = $('#'+settings.quickfinderID).html();
			$('#qf').html(qfContent);
			methods.showOutput(table);
		}
	  });

 
	  $(this).keyup(function() {
		var keyword = $(this).val();
		var table  = $('<table id="search_output_table"/>');
		var count = 0;
		for(var i = 0; i < window.myKeys.length; i++){
		  var _regex = new RegExp( "^" + keyword + "\w*", "i");
		  if(window.myKeys[i].match(_regex)){
			var tr = $('<tr></tr>');
			var td = $('<td class="keywordCol">'+window.myKeys[i]+'</td>');
			td.click(function() {
			  methods.setKeyword($(this).text());
			})
			td.appendTo(tr);
			var td = $('<td></td>')
			td.text(settings.hitBefore + window.myWeight[window.myKeys[i]] + ' ' + settings.hitLabel + settings.hitAfter);
			td.appendTo(tr);
			tr.appendTo(table);
			if (count == settings.maxKeywords - 1) {
			  break;
			}
			count++;
		  }
		}
		
		methods.showOutput(table)
		$('#search_output_table').addClass('table_block');
	  });
	  
	  $(this).blur(function() {
		setTimeout(function(){$('#search_output').slideUp();}, 500);
	  });
    });
  };
})( jQuery );

