$(function() {
	$('select').hide();

	$('select').each(function() {

		function slide ( event, ui ) {
			scrollContent.css( "margin-top", Math.round((100-ui.value) / 100 * ( scrollPane.height() - scrollContent.height() )));
			//scrollContent.css( "margin-top", (ui.value*-1)+'%' );
		}

		var selected = false;
		html = '<div class="options"><div class="options_list">';
		$('option', this).each(function(i) {
			if(i==0)
			selected = $(this).text();
			
			if($(this).attr('selected'))
			selected = $(this).text();
		

			html += '<div class="option">'+$(this).text()+'</div>';
		})
		if(selected==false)
		selected = '';

		html += '</div></div><div class="choose">'+selected+'</div>';

		$(this).before(html);


		var $select = $(this).parent();
		
		var options_height = $('option', this).length*$('.option:first', $select).height();
		var select_height = $('.options', $select).height();

		if(options_height > select_height)
		{
			var scrollPane = $('.options', $select);
			var	scrollContent = $('.options_list', $select);

			$select.prepend('<div class="scrollbar_bg"><div class="scrollbar"><div></div>');
			
			var scrollbar = $('.scrollbar', $select).slider({
				slide: slide,
				change: slide,
				orientation: 'vertical',
				value:100
			});

			$('.options', $select).mousewheel(function(e, delta) {
				delta = e.originalEvent.wheelDelta/-120;
				scrollbar.slider("value", scrollbar.slider("value") + (delta*-5));
				return false;
			});

		}
		
		if($select.hasClass('hide_it'))
		$select.hide();

		$('.options, .scrollbar_bg', $select).hide();
		

	});

	$('body').click(function() {
		$('.select').removeClass('select_active')
		$('.options, .scrollbar_bg', '.select').hide();
	})

	$('.select .option').live('click', function() {
		var $select = $(this).parents('.select');

		var index = $(this).index();
		$('select option:eq('+index+')', $select).attr('selected', true);
		$('select', $select).change();

		$('.choose', $select).text($(this).text());
		$('.select').removeClass('select_active')
		$('.options').hide();
		
		return false;
	});

	$('.select').live('click', function() {
		$('.options, .scrollbar_bg', '.select').hide();
		$(this).addClass('select_active');
		$('.options, .scrollbar_bg', this).show();
		return false;
	});

	$.fn.updatePlatinumSelect = function() {
		var $select = $(this).parents('.select');

		html = '';
		selected = false;
		$('option', this).each(function(i) {
			if(i==0)
			selected = $(this).text();
			
			if($(this).attr('selected'))
			selected = $(this).text();
		
			html += '<div class="option">'+$(this).text()+'</div>';
		})
		
		$('.choose', $select).text(selected);

		$('.options', $select).html(html);


	}
});
