/**
 * @author balazs.suhajda
 */
var kum = kum || {};

kum.linkdropdown = ( function () {
	var selector = '.linkselector',
		margin = 30,	// 	px from bottom to open selector upwards
		delay = 200,	//	before closing
		duration = 200;	//	animation
	
	var init = function () {
		$( selector )
			.find( ' > ul > li' )
			.each( setup );
	};
	
	var setup = function () {
		var el = this;
		this.list = $( this ).find( 'ul' );
		this.h = this.list.height();
		this.list.h = this.list.appendTo( 'body' ).height();
		$( this )
			.mouseover( function ( e ) {
				e.stopPropagation();
				mouseover( el )
			})
			.mouseout(function( e ){
				e.stopPropagation();
				mouseout( el )
			});
		this.list
			.hide()
			.height( 0 )
			.width( $( this ).width() )
			.mouseover( function ( e ) {
				e.stopPropagation();
				mouseover( el );
			})
			.mouseout( function ( e ) {
				e.stopPropagation();
				mouseout( el );
			});
	};
	
	var mouseover = function ( el ) {
		clearTimeout( el.t );
		var offset = $( el ).offset();
		$( el.list )
			.css({
				top : offset.top + el.h,
				left : offset.left,
				bottom : ''
			});
		if ( el.list.h + offset.top + margin > $( window ).height() + $( window ).scrollTop() )
			$( el.list ).css({
				top : '',
				bottom : $( window ).height() - offset.top
			});
			
		$( el.list ).stop().animate({
				height : el.list.h
			}, duration );
	};
	
	var mouseout = function ( el ) {
		el.t = setTimeout( function () {
			$( el.list ).stop().animate({
				height : 0
			}, duration );
		}, delay );
	};
	
	return {
		init: init
	}
})();

$( window ).load( kum.linkdropdown.init );
