/*
 * jQuery selectbox plugin adapted by Suxesiv
 *
 * 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$
 * Version: sx0.8
 * V-Date: 28.05.09
 * 
 * Todo:
 *  - Navigation mit Pfeiltasten, wenn bereits mit Mouseover etwas gewählt wurde.
 *  - Zum gewählten Punkt scrollen.
 * 
 * Changelog :
 *  - 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 || "selected";
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var li_id_prefix = elm_id + '_input_';
	var active = -1;
	var selected_id = '';
	var inFocus = false;
	var hasfocus = 0;
	var elm_cnt = 0; //counts the elements
	var elm_cnt_ar = new Object();
	//jquery object for select element
	var $select = $(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('<div class="selectbox_left"></div>').before($input).before($container);
	
	init();


	
	$input
	.click(function(){
		$container.toggle();
		//moveSelect(0); // sets selected field back
		var sel_value = $('#'+elm_id).val();
		$("#"+$container.attr("id")+' .selected').removeClass('selected');
		$('#'+li_id_prefix+sel_value).addClass('selected');
		
		if (opt.debug) console.log('Click:'+li_id_prefix+sel_value );
		
		//$('#'+elm_id+'_container').scrollTop(0);
		//var x = $('#'+li_id_prefix+sel_value).offset().top;
		//x = parseInt(x);
		//if (opt.debug) console.log('stop: '+x );
		//$('#'+elm_id+'_container').scrollTop(x);
		
	    var divOffset = $('#'+elm_id+'_container').offset().top;
	    var pOffset = $('#'+li_id_prefix+sel_value).offset().top;
	    var pScroll = pOffset - divOffset;
		if (opt.debug) console.log( 'stop: '+pScroll );
	    $('#'+elm_id+'_container').scrollTop( pScroll );
	})
	.focus(function(){
	   if (opt.debug) console.log('input focus');
	})
	.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 !
				setCurrent();
				hideMe();
				break;
		}
	})
	.blur(function() {
		if (opt.debug) console.log('input: blur;');
		
		
		
		if ( hasfocus==0 ) {
			hideMe();
		}else{
			$input.focus( );
		}
	});
	
	$('#'+elm_id+'_container')
	.scroll(function(event) {
		var sel_value = $('#'+elm_id).val();
	    var divOffset = $('#'+elm_id+'_container').offset().top;
	    //var pOffset = $('#'+li_id_prefix+sel_value).offset().top;
		var pOffset = $('#'+elm_id+'_container'+' .selected').offset().top;
	    var pScroll = pOffset - divOffset;
		
		if (opt.debug) console.log( 'ssss: '+divOffset+'; poff:'+pOffset+'; pscroll:'+pScroll );
	})
	.mouseover(function(event) {
		hasfocus=1;
	})
	
	.mouseout(function(event) {
		hasfocus=0;
	});
	
	function hideMe() {
		hasfocus = 0;
		$container.hide();
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		var width = $input.css('width');
		$container.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	function setupInput(options) {
		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
		$input.width( parseInt($('#'+elm_id).width())-4 );
		
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass('selected');

		$(lis[active]).addClass('selected');
	}
	
	function setCurrent() {
		var li = $("li."+'selected', $container).get(0);
		//var el = (li.id).replace(li_id_prefix,"");
		var el = (li.id).substr( li_id_prefix.length );
		
		if (opt.debug) console.log('el: '+el );
	
		$input.val($(li).text());

		$('#'+elm_id).val(el);
		if (opt.debug) console.log('element value : '+$('#'+elm_id).val() );
		$('#'+elm_id).change();
		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 + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).text());
				$(li).addClass('selected');
				active = elm_cnt;
				selected_id = parentid + '_' + $(this).val();
			}
			ul.appendChild(li);
			elm_cnt_ar[ this.id ] = elm_cnt;
			elm_cnt += 1;
			
			
			
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('out on mouseover : elm_cnt:'+elm_cnt_ar[ this.id ]+'_'+this.id );
				$("#"+$container.attr("id")+' .selected').removeClass('selected');
				active = elm_cnt_ar[ this.id ];
				jQuery(event.target, $container).addClass('selected');
			})
			
			.mouseout(function(event) {
				hasfocus = 0;
				if (opt.debug) console.log('out on mouseout : '+this.id );
			})
			
			.click(function(event) {
				if (opt.debug) console.log('click on :'+this.id);
				$(this).addClass('selected');
				setCurrent();
				hideMe();
			});
			
		});
		

		
		return ul;
	}
	
};

$(document).ready(function(){
	$('select').selectbox();
});



