// jQuery csb (custom selectbox) plugin
// version 1.0
// Author Mihkel Oviir

(function(jQuery){
	
	jQuery.fn.csb = function(options) {
		jQuery(this).hide();

		var style = options.style;
		var mode = options.mode;

		var thisid = jQuery(this).attr('id');
		var selected = this.find("option[selected]");

		if (mode == 'link') var selects = this.find("option:not([selected])");
		else var selects = this.find("option");
		jQuery(this).parent().append('<dl id="'+thisid+'" class="'+style+'"></dl>');
		jQuery('dl#'+thisid).append('<dt><a name="' + selected.val() + '">' + selected.text() + '</a></dt>');
		jQuery('dl#'+thisid).append('<dd><ul></ul></dd>');
		selects.each(function(){
			jQuery('dl#'+ thisid + " dd ul").append('<li><a name="' + jQuery(this).val() + '">' + jQuery(this).text() + '</a></li>');
		});

		jQuery('.'+style+' dt a').click(function() {
			jQuery('.'+style+' dd ul').toggle();
			return false;
		});

		jQuery(document).bind('click', function(e) {
			var $clicked = jQuery(e.target);
			if (! $clicked.parents().hasClass(style)) jQuery('.'+style+' dd ul').hide();
		});

		if (mode == 'link') {
			jQuery('.'+style+' dd ul li a').live('click',function() {
				jQuery('.'+style+' dd ul').hide();
				var functvar = jQuery(this).attr('name');
				
				// now call a callback function
				if(typeof options.callback == 'function'){
					options.callback(functvar);
				}
				return false;
			});
		}
		else {
			jQuery('.'+style+' dd ul li a').live('click',function() {
				var text = jQuery(this).html();
				jQuery('.'+style+' dt a').html(text);
				jQuery('.'+style+' dd ul').hide();

				var source = jQuery('select#'+thisid);
				var functvar = jQuery(this).attr('name');
				source.val(functvar);
				
				// now call a callback function
				if(typeof options.callback == 'function'){
					options.callback(functvar);
				}
				return false;
			});
		}	
	}
})(jQuery); // plugina lõpp
