// JavaScript Document
(function($) {
	$.fn.newSelect = function(options) {
		var opts = $.extend({}, $.fn.newSelect.defaults, options);
		return this.each(function() {
			var $this 					= $(this);
			$this.opts 					= $.extend({}, opts);
			$this.opts.newSelect = $('<div class="newSelect"><input type="hidden"  value="'+$this.val()+'" name="'+$this.attr('name')+'"></div>');
			$this.opts.newSelect.insertAfter($this);
			$('<label>'+$this.find(':selected').text()+'</label><div class="hider"><ul></ul></div>').appendTo($this.opts.newSelect);
			$this.find('option').each(function(){
				indent = '';
				if($(this).attr('rel')){
					indent = 'padding-left:' + (parseInt($(this).attr('rel'))*20) + 'px';
				}
				$node = $('<li><a href="'+$(this).attr('value')+'" style="'+(indent)+'">' + ($(this).attr('label') ? $(this).attr('label'): $(this).html())+'</a></li>');
				$node.find('a').bind('click', function(event){
													   
					$this.opts.newSelect.find('label').html($(this).html());
					$this.opts.newSelect.find('input').val($(this).attr('href').replace($('base').attr('href'),''));
					
					$.fn.newSelect.close($this,200);
					$.fn.newSelect.checkDate($this);
					event.preventDefault();
				});
				$node.appendTo($this.opts.newSelect.find('.hider ul'));
			});
			
			$this.opts.newSelect.find('.hider').css('width',$this.opts.newSelect.find('label').outerWidth()+'px');
			$this.opts.newSelect.find('label').bind('click',function(){
				if($this.opts.status == 'closed'){
					$.fn.newSelect.open($this);
				}else{
					$.fn.newSelect.close($this);
				}
			})
			$this.remove();
			$.fn.newSelect.checkDate($this);
		});
	};
	
	$.fn.newSelect.defaults = {
		status: 'closed'
	};
	
	
	
	$.fn.newSelect.checkDate = function($this){
		if($this.opts.newSelect.find('input').attr('name') == 'periode'){
			if($('.fromtill[rel='+$this.opts.newSelect.find('input').val()+']').length > 0){
				$('.fromtill').show();	
			}else{
				$('.fromtill').hide();	
			}
		}
	};
	
	
	$.fn.newSelect.open = function($this, speed){
		if(!speed) speed = 500;
		$this.opts.status = 'open';
		$this.opts.newSelect.find('.hider').stop().animate({height:$this.opts.newSelect.find('ul').outerHeight()+'px'},speed);
	//	$this.opts.newSelect.bind('mouseout', function(){
	//		$.fn.newSelect.close($this,200);							
	//	});
	};
	
	$.fn.newSelect.close = function($this, speed){
	//	$this.opts.newSelect.unbind('mouseout');
		if(!speed) speed = 500;
		$this.opts.status = 'closed';
		$this.opts.newSelect.find('.hider').stop().animate({height:'0px'},speed);
	};
})(jQuery);
