/*
 * 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)
 *
 * Revision: $Id: jquery.selectbox.js,v 1.1 2008-11-07 10:20:14 dk Exp $
 * 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.emptyClass = opt.selectedClass || "empty";
	opt.paddingRight = opt.paddingRight || 14;
	opt.debug = opt.debug || false;

	var elm_id = selectobj.id;
	clear();
	
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $0(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object
	var $input = setupInput(opt);
	// hide select and append newly created elements
	$select.hide().before($input).before($container);


	init();

	$input
	.click(function(){
		$container.toggle();
	})
	.focus(function(event){
		if ($container.not(':visible')) {
			inFocus = true;
		}
	})
	.keydown(function(event) {
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$0('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
				hideMe();
				break;
		}
	})
	.blur(function() {
		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($0.browser.msie || $0.browser.safari // check for safari too - workaround for webkit
			){
				if(document.activeElement.getAttribute('id') == null || document.activeElement.getAttribute('id').indexOf('_container')==-1){
					hideMe();
				} else {
					$input.focus();
				}
			} else {
				hideMe();
			}
		}
	});


	function hideMe() {
		hasfocus = 0;
		$container.hide();
	}

	function clear() {
		if(elm_id.length > 0)
		{
			jQuery('#'+elm_id+'_input').remove();
			jQuery('#'+elm_id+'_container').remove();
		}
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		var width = $input.width();
		var cssWidth = $input.css('width');
		var cssPaddingRight = $input.css('padding-right');
		if (cssWidth != 'auto' && cssWidth.substr(cssWidth.length-1,1) != '%')
		{
			//apply padding right
			cssWidth = parseInt(cssWidth.substr(0, cssWidth.length-2)) + parseInt(cssPaddingRight.substr(0, cssPaddingRight.length-2));
			$input.css('width',(cssWidth - opt.paddingRight)+'px');
			$container.css('width', cssWidth+'px');
		}
		else
		{
			$container.width(width);
			//apply padding right
			$input.width(width - opt.paddingRight);
		}
		$input.css('padding-right',opt.paddingRight+'px');

		if(jQuery.browser.msie && jQuery.browser.version.match(/^6/))
		{
			if ($container.height() > 200)
			{
				$container.height(200);
			}
		}
	
	}

	function setupContainer(options) {
		var container = document.createElement("div");
		$container = jQuery(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		$container.css('display','none');

		return $container;
	}

	function setupInput(options) {
		var input = document.createElement("input");
		var $input = jQuery(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.addClass(options.emptyClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		if ($select.css('width') != 'auto')
		{
			$input.css('width', $select.css('width'));
		}
		else
		{
			$input.width($select.width());
		}
		$input.css('border', $select.css('border'));

		return $input;
	}

	function moveSelect(step) {
		var lis = jQuery("li", $container);
		if (!lis || lis.length == 0) return false;
		active += step;
		//loop through list
		if (active < 0) {
			active = lis.size();
		} else if (active > lis.size()) {
			active = 0;
		}
		scroll(lis, active);
		lis.removeClass(opt.hoverClass);

		jQuery(lis[active]).addClass(opt.hoverClass);
	}

	function scroll(list, active) {
		var el = jQuery(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() {
		var li = jQuery("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		if (el=='')
		{
			$input.addClass(opt.emptyClass);
		}
		else
		{
			$input.removeClass(opt.emptyClass);
		}
		$select.val(el);
		$input.val(jQuery(li).text());
		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() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + jQuery(this).val());
			li.innerHTML = jQuery(this).html();
			if (jQuery(this).val()=='')
			{
				jQuery(li).addClass(opt.emptyClass);
			}
			if (jQuery(this).is(':selected')) {
				$input.val(jQuery(this).text());
				jQuery(li).addClass(opt.currentClass);
				if (jQuery(this).val()!='')
				{
					$input.removeClass(opt.emptyClass);
				}
			}
			ul.appendChild(li);
			jQuery(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
				var fl = jQuery('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				jQuery('li.'+opt.currentClass).removeClass(opt.currentClass);
				jQuery(this).addClass(opt.currentClass);
				setCurrent();
				//$select.change();
				$select.get(0).blur();
				hideMe();
				$select.change();
			});
		});
		return ul;
	}
};

