/* dropdown plugin */
(function($){  
	$.fn.dropdown = function(options) {  

		var defaults = $.extend({ timeout : 2000 }, options);
		//var options = $.extend(defaults, options);  
		var e, dropdown, remsel, timer, over;
		
		$(this).bind('click', function() {
			if(e) out();
			
			e = $(this).parent();
			dropdown = $(e).attr('rel');
			var pos =  $(e).position();
			
			// Pozicije
			var tpos = pos.top;
			var lpos = (pos.left+$(dropdown).width() > $(window).width()) ? $(window).width()-$(dropdown).width()-22 : pos.left;
			var rpos = $(e).parent().width()+$(e).parent().position().left;
			var rdd = lpos+$(dropdown).width();
			var top_w = (rpos < rdd) ? rdd-rpos-3 : 0;
			
			// Da li je tab bio selektovan? Dodaj stavi ga da bude
			if(!$(e).parent().hasClass('selected')) {
				remsel=true;
				$(e).parent().addClass('selected').children(':last').addClass('current');
			}
			
			// Ako je prvi dodaj mu klasu da se iskljuci zaobljena ivica
			if($(e).prev().length == 0) {
				$(e).parent().addClass('selected-up');
			}
			
			// Prikazi gornji border
			if(top_w > 0) {
				$(dropdown).children('.vrh').width(top_w).show();
				$(e).parent().children('.current').addClass('opened');
			}
			// Otvori dropdown
			$(dropdown)
				.css({ top: tpos+20, left: lpos })
				.slideDown(100, function() {					
					// close on click
					$(document).bind('click.dropdown',function(e) {				
						if(!($(e.target).is(dropdown) || $(e.target).parents().is(dropdown))) 
							out();
					});	
					
					// close on timeout
					timeout();
					$(dropdown)
						.bind('mouseleave.dropdown', function() {timeout();})
						.bind('mouseenter.dropdown', function() {clearTimeout(timer);});
				});
				
			return false;
		});
		
		// Zatvaranje dropdown-a
		function out() {
			$(dropdown).hide();
			if(remsel) {
				remsel=false;
				$(e).parent().removeClass('selected').children(':last').removeClass('current').removeClass('opened');
			} else {
				$(e).parent().children('.current').removeClass('opened');
			}
			
			$(e).parent().removeClass('selected-up');
			
			
			$(document).unbind('click.dropdown');
			$(dropdown)
				.unbind('mouseleave.dropdown')
				.unbind('mouseenter.dropdown');
			clearTimeout(timer);
			e = false;
		}
		
		// Zatvaranje dropdown-a nakon X vremena
		function timeout() {
			timer = setTimeout(out, defaults.timeout);
		}
	};
})(jQuery);