/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *

 * Version: 0.6
 * 
 * Changelog :
 *  Version 0.6
 *  - Fix IE scrolling problem
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected";
	opt.debug = opt.debug || false;
	opt.maxLength = opt.maxLength || 0; // Maximum number of characters to be shown in the text box
	
	var elm_id = selectobj.id;
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	
	/*
	 * fromFocus variable is used to set the value as 1 as soon as 
	 * the focus event is triggered on the input field, thereby 
	 * enabling to control the toggle of the drop-down on the click events. 
	 */
	var fromFocus = 0; 
	
	var previousText;
	
	
	// global storage object for drop-down info, including reset() method
	var dropDownInfo = {
						last:0, 
						accumString:"", 
						delay:500,
						timeout:null, 
						reset:function() {this.last=0; this.accumString=""}
					};
	
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	
	init();
	
	$input
	.click(function(){
    	if (!inFocus) {
		  $container.toggle();
		} else {
			/*
			 * when a click is made on the input field two events are triggered 
			 * in the following order.
			 * 1. Focus event
			 * 2. Click event
			 *
			 * During Focus event, fromFocus value is set to 1 and inFocus is set to true.
			 * Container will be visible now. 
			 * Control then jumps to click event and since inFocus is true, 
			 * flow comes into this else part. If the check "if (fromFocus == 0)" is not there,
			 * then container will be toggled and user has to click one more time. To prevent
			 * this, fromFocus is checked for 0 and then toggled. 
			 *
			 * Once the focus is event is triggered, for all the future mouse clicks 
			 * only click events are triggered. So fromFocus value has to be set to "0" to provide
			 * the user will drop-down toggle and hence after the check the fromFocus value is set to 0.
			 */
			if (fromFocus == 0)
			{
				$container.toggle();
				if(opt.debug)  console.log('container toggled from click event ');
			}
			fromFocus = 0;
		}	
	})
	.focus(function(){
		
	   if ($container.not(':visible')) {
	       inFocus = true;
	       fromFocus = 1;
	       $container.show();
	   }
	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 36: // Home
				event.preventDefault();
				handleHomeAndEndKey(event.keyCode);
				dropDownInfo.reset();
				break;
			case 35: // End
				event.preventDefault();
				handleHomeAndEndKey(event.keyCode);
				dropDownInfo.reset();
				break;
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				dropDownInfo.reset();
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				dropDownInfo.reset();
				break;
			case 9:  // tab 
				// Commented the following line to allow the default functionality of tab key.
				// event.preventDefault(); // seems not working in mac !
				$container.find('li.'+opt.hoverClass).trigger('click');
				break;
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$container.find('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
			default:
				//$select.keydown(event);
				if(opt.debug) console.log('Event KeyCode = '+event.keyCode)
				if ( (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90) ) {
					event.preventDefault();
					reflectKeyPressEvent(event, event.keyCode);
				}
				break;
		}
	})
	.blur(function() {
    	if (!inFocus) {
    	  if ($container.is(':visible') && hasfocus <= 0 ) {
		  	$container.hide();
		  }
		}
		
		if ($container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
		  // Workaround for ie scroll - thanks to Bernd Matzner
		  if($.browser.msie || $.browser.safari){ // check for safari too - workaround for webkit
			if(document.activeElement.getAttribute('id').indexOf('_container')==-1){
			  hideMe();
			} else {
			  $input.focus();
			}
		  } else {
			hideMe();
		  }
		}
		
	});


	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
	}
	
	/* Modified for fidoGarden to include the padding during the width calculation */
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		//var width = $input.innerWidth();
		var width = $input.outerWidth();
		if(width == 0 && $select.css("width") != 0) {
			width = $select.css("width");
		}
		$container.width(width);
    }
	
	function setupContainer(options) {
		var nodeID = elm_id+"_container";
		
		if (document.getElementById(nodeID) != null ) {
			var container = document.getElementById(nodeID);
			$container = $(container);
			return $container.empty();
		} else {
			var container = document.createElement("div");
			$container = $(container);
			$container.attr('id', elm_id+'_container');
			$container.addClass(options.containerClass);
			return $container;
		}
	}
	
	function setupInput(options) {
		var nodeID = elm_id+"_input";
		
		if (document.getElementById(nodeID) != null ) {
			var input = document.getElementById(nodeID);
			$input = $(input);
			return $input;		
		} else {
			var input = document.createElement("input");
			var $input = $(input);
			$input.attr("id", elm_id+"_input");
			$input.attr("type", "text");
			$input.addClass(options.inputClass);
			$input.attr("autocomplete", "off");
			$input.attr("readonly", "readonly");
			$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
			return $input;
		}
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis || lis.length == 0) return false;
		active += step;
	    //loop through list

		if (active < 0) {
			active = lis.size() - 1;
		} else if (active >= lis.size()) {
			active = 0;
		}
		//alert(active);
		scroll(lis, active);
		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
		reflectHighlightedSelection();
	}
	
	/**
	  * Method to handle the "Home" and "End" keys keyboard events. 
	  * Home - Takes the user to the start of the list in the selectbox. 
	  * End - Takes the user to the end of the list in the selectbox.
	  */
	function handleHomeAndEndKey(currentKeyCode) {
		var lis = $("li", $container);
		if (!lis || lis.length == 0) return false;
		var destIndex ;
		
		if (currentKeyCode == 36) {

			// Home Key in the keyboard. Take the user to start of the list in the select box.
			destIndex = 0;

		} else if (currentKeyCode == 35) {

			// End key in the keyboard. Take the user to the end of the list in the select box.
			destIndex = lis.size() - 1;

		}
		// Scroll to the element at the destIndex of the list
		scroll(lis, destIndex);

		// Remove hoverClass style for entire li
		lis.removeClass(opt.hoverClass);

		// Add hover style to the element at the destIndex in the select box.
		$(lis[destIndex]).addClass(opt.hoverClass);

		reflectHighlightedSelection();
	}
	
	function reflectHighlightedSelection() {
		// get the li with hoverClass set so that the value of this li is reflected in the input box.
		var li = $("li."+opt.hoverClass, $container).get(0);
		// Pass "false" so that select onchange event will not be triggered.
		setCurrent(li, "false");
		return true;
	}
	
	function reflectKeyPressEvent(currentEvent, currentKeyCode) {
		// Retrieve the key character from the key code.
		var currentKeyChar =  String.fromCharCode(currentKeyCode).toUpperCase();
		var optionsList = $("li", $container);
		if (!optionsList || optionsList.length == 0) return false;
		
		var now = new Date();
				
		// First Time iterate from active+1 until the end of optionsList
		returnVal = iterateAndFetchMatchingValue (active+1, optionsList.length, optionsList, currentEvent, currentKeyChar, now);

		// Then iterate from 0 until active index in the optionsList.
		if (returnVal) {
			iterateAndFetchMatchingValue (0, active, optionsList, currentEvent, currentKeyChar, now);
		}

		// reset global object
		dropDownInfo.reset();
		return true;		
	}	
	
	/**
	  * This Method iterates through the list and highlights the text matching the 
	  * key event triggered.
	  * Following are the parameters to the function:
	  * startIndex - starting index in the list where iteration should begin
	  * endIndex - ending index in the list where iteration should end
	  * currentKeyChar - current key pressed in uppercase
	  * now - current Date
	  */
	function iterateAndFetchMatchingValue(startIndex, endIndex, list, currentEvent, currentKeyChar, now) {
		var displayTxt;
		for (var i = startIndex; i < list.length; i++) {
			displayTxt = $(list[i]).text(); 
			if (displayTxt.indexOf(currentKeyChar) == 0 && dropDownInfo.accumString.indexOf(displayTxt) == -1) {
				dropDownInfo.accumString +=displayTxt;
				// stop any previous timeout timer
				clearTimeout(dropDownInfo.timeout);
				// store current event's time in object 
				dropDownInfo.last = now;
				// reset dropDownInfo properties in [delay] ms unless cleared beforehand
				dropDownInfo.timeout = setTimeout(reset, 500);
				
				// Set the current index to active global variable so that key up or key down will behave correctly
				active = i;
				
				// scroll is used to scroll the list to the matching index.
				scroll(list, i);
				list.removeClass(opt.hoverClass);
				$(list[i]).addClass(opt.hoverClass);
				reflectHighlightedSelection();
				// prevent default event actions and propagation
				currentEvent.cancelBubble = true;
				currentEvent.returnValue = false;
				return false;
			}
		}
		return true;
	}

	function reset() {dropDownInfo.reset();}
	
	function scroll(list, active) {
      var el = $(list[active]).get(0);
      var list = $container.get(0);
      
      if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
        list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;      
      } else if(el.offsetTop < list.scrollTop) {
        list.scrollTop = el.offsetTop;
      }
	}
	
	function setCurrent(li, triggerChange) {
		//var li = $("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		var elementArray = el.split('|index~');
		var liText = $(li).text();
		$select.val(elementArray[0]);
		if(navigator.appName=="Microsoft Internet Explorer" && opt.maxLength > 0)
			liText = liText.substr(0, opt.maxLength);
		$input.val(liText);
		if (triggerChange == 'true') {
			$select.trigger('change'); // Added for garden navigation
		}
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function(i) {
			var li = document.createElement('li');
			// Append "|index~"+indexValue so that this is used to identify the position of current value in the list.
			li.setAttribute('id', parentid + '_' + $(this).val() + '|index~' + i);
			li.innerHTML = $(this).html();
			li.setAttribute('style', $(this).attr("style"));
			if ($(this).is(':selected')) {
				var liText = $(this).text();
				if(navigator.appName=="Microsoft Internet Explorer" && opt.maxLength > 0)
					liText = liText.substr(0, opt.maxLength);
				$input.val(liText);
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				var array = (this.id).split('|');
				var subArray = array[array.length - 1];
				var activeIndex = subArray.split('~');
				var lis = $("li", $container);
				/*
				 * Set the value of the active  global variable so that 
				 * keyboard up and down events takes the user to the corresponding elements
				 * in the select box.
				 */
				active = parseInt(activeIndex[1]);
				if (opt.debug) console.log('over on : '+this.id);
				// Remove hoverClass style for entire li
				lis.removeClass(opt.hoverClass);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				active = 0;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			    var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass).removeClass(opt.currentClass); 
				$(this).addClass(opt.currentClass);
				setCurrent(this, "true");
				//$select.change();
				$select.get(0).blur();
				hideMe();
			});
		});
		return ul;
	}
};
