// JavaScript Document
(function($){
	$.setup = function(t, options){
		var defaults = {
			width: '200px'
		};
		var options = $.extend({}, defaults, options);
		var select = {
			create: function() {
				text = $('option:selected', t).text();
				$(t).hide();
				this.container =$('<div></div>')
					.width(options.width)
					.addClass('jSelectContainer')
					.insertBefore(t);
				
				MAIN = this;
				// add Selected
				this.field = $('<div></div>')
					.addClass('jSelectField')
					.appendTo(this.container);
				// addButton
				this.button = $('<div></div>')
					.addClass('jSelectButton')
					.appendTo(this.field)
					.hover(
						// подсветка кнопки
						function(){
							if($(this).hasClass('jSelectButtonUp')){
								$(this).addClass('jSelectButtonUpHover');
							} else {
								$(this).addClass('jSelectButtonHover');
							}
						},
						function(){
							$(this).removeClass('jSelectButtonHover').removeClass('jSelectButtonUpHover');
						}
					)
					.click(function(){
						// показать убрать список						
						if($(MAIN.opt).css('display') == 'none'){
							$(MAIN.opt).slideDown('fast');
							$(this).addClass('jSelectButtonUp');
						} else {
							$(MAIN.opt).slideUp('fast');
							$(this).removeClass('jSelectButtonUp');	
						}
					});
				// добавляем текст
				this.textSelected = $('<p></p>')
					.text(text)
					.appendTo(this.field);
				this.opt = $('<div></div>')
					.addClass('jSelectList')
					.appendTo(this.container);
				
				this.optUl = $('<ul></ul>').appendTo(this.opt);
				optUl = this.optUl;
				$('option', t).each(function(i, item){
					$('<li></li>')
						.text($(item).text())
						.attr('rel', $(item).val())
						.hover(
							function(){
								$(this).addClass('jSelectListItemHover');
							},
							function(){
								$(this).removeClass('jSelectListItemHover');
							}
						)
						.click(function(){
							what = $(this).attr('rel');
							$('option', t).removeAttr('selected');
							$('option[@value='+what+']').attr('selected', 'selected');
							$(MAIN.textSelected).text($(this).text());
							$(MAIN.opt).slideUp('fast');
							$(MAIN.button).removeClass('jSelectButtonUp');
						})
						.appendTo(optUl);
				});
			}
		}
		select.create();
		t.Select = select;
	};
	
	$.fn.jSelect = function(options){
		return this.each( function() {
			$.setup(this, options);
		});
	};
	
})(jQuery);
