DropDown = function (domSelect) {
	this.isOpen = false;

	this.init(domSelect);
}

DropDown.prototype.init = function(domSelect) {
	var defaultIndex = domSelect.selectedIndex;

	this.initInput(domSelect);
	this.initSelect(domSelect);

	var option = $("a:eq("+defaultIndex+")", this.jOptionsCont);
	this.selectItem(option[0]);
}


DropDown.prototype.initInput = function(domSelect) {
	this.domInput = document.createElement("input");
	this.domInput.type = "hidden";
	this.domInput.name = domSelect.name;
	domSelect.parentNode.insertBefore(this.domInput, domSelect);
}

DropDown.prototype.initSelect = function(domSelect) {
	//начало HTML кода
	var sHtml = "<div><div class=\"b-pix\"><span class='current'></span><div class='options'>";
	//список опций
	for(var i=0; i<domSelect.options.length; i++) {
		var option = domSelect.options[i];
		sHtml += "<a href='#"+option.value+"'>"+option.innerHTML+"</a>"
	}
	//конец HTML кода
	sHtml += "<ins class='lb'></ins><ins class='rb'></ins></div><ins class='strelka'></ins><ins class='lt'></ins><ins class='rt'></ins><ins class='lb'></ins><ins class='rb'></ins></div>";
	this.jSelect = $(sHtml);
	//устнавливаем класс
	this.jSelect[0].className = domSelect.className;		
	//выделяем основные элементы
	this.jCurrent = $(".current", this.jSelect);
	this.jOptionsCont = $(".options", this.jSelect);
	//устанавливаем обработчики событий
	var t = this;
	this.jSelect.click(function(){t.openOptions();});
	$("a",this.jOptionsCont).click(function(){t.selectOption(this)});
	//отображаем элеменнт
	$(domSelect).before(this.jSelect);
	$(domSelect).remove();
	//определяем ширину
	this.jOptionsCont.css({width: "100%", opacity: 0});
	setTimeout(function(){
		var as = $("a", t.jOptionsCont[0]);
		var maxWidth = 50;
		var w;
		for(var i=0; i<as.length; i++) {
			w = as[i].offsetWidth;
			if(w > maxWidth) 
				maxWidth = w;
		}
		var setW = maxWidth + 20;
		t.jOptionsCont.css({width: setW, opacity: 1});
		t.jCurrent.parent().css('width', $.boxModel ? (setW+2) : setW);
		t.jOptionsCont.hide();
	}, 100);

} 

DropDown.prototype.selectItem = function(option) {
	if(option) {
		this.jCurrent.html(option.innerHTML);
		this.domInput.value = option.href.match(/\d+$/)[0];
	}
}

DropDown.prototype.openOptions = function() {
	if(this.isOpen)
		return;

	this.jOptionsCont.show();
	this.isOpen = true;

	var t = this;
	this.closeFun = function(){t.closeOptions();};
	setTimeout(function(){	$(document.body).bind("click", t.closeFun);},10);
}

DropDown.prototype.closeOptions = function() {
	this.jOptionsCont.hide();
	this.isOpen = false;

	$(document.body).unbind("click", this.closeFun);
}

DropDown.prototype.selectOption = function(option) {
	this.selectItem(option);
	var t = this;
	setTimeout(function(){	t.closeOptions();}, 10);
	return false;
}

$().ready(function() {
	$("select.j_select").each(function() {
		new DropDown(this);
	});
});
