/**
 * @author balazs.suhajda
 */
(function ($) {
	$.fn.linkSelector = function (options) {
		var config = {
			margin 			: 30,						// 	px from bottom to open selector upwards
			delay 			: 200,						//	before closing
			duration 		: 200,						//	animation
			listSelector 	: 'ul'
		};
		
		$.extend(config, options || {});
	
		this.each(function () {
			var el = $(this);
			el[0].list = $(this).find(config.listSelector);
			el[0].list.h = el[0].list.height();
			el
				.mouseover(function(){
					mouseover(el)
				})
				.mouseout(function(){
					mouseout(el)
				});
			
			//	adding dropdown to end of body to overcome ie z-index issues
			if ('v' == '\v') {
				el[0].list
				.mouseover(function(){
					mouseover(el)
				})
				.mouseout(function(){
					mouseout(el)
				})
				.appendTo('body');	
			} 
			el[0].h = el.outerHeight();
			el[0].list
				.hide()
				.height(0)
		});
	
		var mouseover = function (el) {
			clearTimeout(el[0].t);
			var offset = ('v' == '\v') ? el.offset() : el.position();
			$(el[0].list)
				.show()
				.css({
					top : offset.top + el[0].h,
					left : offset.left,
					bottom : ''
				});
			if (el[0].list.h + offset.top + config.margin > $(window).height() + $(window).scrollTop())
				$(el[0].list).css({
					top : '',
					bottom : $(window).height() - offset.top
				});
				
			$(el[0].list).stop().animate({
					height : el[0].list.h
				}, {
					duration : config.duration
				});
		};
		
		var mouseout = function (el) {
			clearTimeout(el[0].t);
			el[0].t = setTimeout(function () {
				$(el[0].list).stop().animate({
					height : 0
				},{
					duration : config.duration,
					complete : function () {
						el[0].list.hide()
					}
				});
			}, config.delay);
		};
		
		return this
	}
})(jQuery);
