$(function(){
	$('select').each(function(index){
		var width=$(this).outerWidth(),
			width=width<150?150:width,
			ulWidth=width+8,
			ulHeight=$('option, optgroup',this).size()>10?'200px':'auto',
			max=0;
		$(this).after('<div class="dropdown"><input type="hidden" name="'+$(this).attr('name')+'" value="'+$(this).find('option:selected').attr('value')+'" readonly="readonly"/><span style="width: '+(width+12)+'px"><b style="width: '+(width-30)+'px">'+$(this).find('option:selected').text()+'</b></span><ul style="width: '+ulWidth+'px;height: '+ulHeight+'"></ul></div>');
		$('optgroup, > option',this).each(function(){
			if (this.tagName.toLowerCase()=='optgroup') {
				$('.dropdown:eq('+index+') ul').append('<li class="optgroup">'+$(this).attr('label')+'</li>');
				$('option',this).each(function(){
					$('.dropdown:eq('+index+') ul').append('<li rel="'+$(this).attr('value')+'" class="grouped">'+$(this).text()+'</li>');
				});
			}
			else $('.dropdown:eq('+index+') ul').append('<li rel="'+$(this).attr('value')+'">'+$(this).text()+'</li>');
		});
		$(this).remove();
	});
	$('.dropdown span')
		.hover(
			function(){$(this).addClass('hover')},
			function(){$(this).removeClass('hover')}
		)
		.bind('mousedown',function(event){
			event=event||window.event;
			event.preventDefault();
			if (!$(this).parent().find('ul').is(':visible')) $('.dropdown').removeClass('up').find('span').removeClass('active').end().find('ul').slideUp('fast');
			$(this).toggleClass('active').parent().toggleClass('up').find('ul').slideToggle('fast');
			$(document).bind('click',function(event){
				event=event||window.event;
				target=event.target||event.srcElement;
				if (!($(target).parent().hasClass('dropdown')||$(target).parent().parent().hasClass('dropdown'))) {
					$('.dropdown').removeClass('up').find('span').removeClass('active').end().find('ul').slideUp('fast');
					$(document).unbind('click');
					$(document).unbind('mousemove');
				}
			});
			$(document).bind('mousemove',function(){return false;});
			return false;
		})
	$('.dropdown li').not('.optgroup')
		.bind('mouseup',function(){
            if (location.href.match('^.*news.*$')) {
                var p = $(this).attr('rel');                
                window.location.href = 'http://axel-holding.ru/news/category/' + p;
            }
			$(this).parent().slideUp('fast').parent().removeClass('up').find('span').removeClass('active').find('b').html($(this).text()).end().end().find('input').attr('value',$(this).attr('rel'));
			$(document).unbind('mousemove');
		})
		.hover(
			function(){$(this).addClass('hover');},
			function(){$(this).removeClass('hover');}
		);
});

