(function ($) {

	var body = $('body');

	function addFixedProperties(dropdown, list, event) {
		var dropdownPos = $(dropdown).offset();

		dropdownPos.top = dropdownPos.top - $(window).scrollTop();

		var zIndex = 99999 + $(list).parents('.dropdown').length;

		$(list).css('position', 'fixed');
		$(list).css('z-index', zIndex);
		$(list).css('max-height', 'inherit');
		$(list).css('overflow', 'inherit');
		$(list).css('overflow-y', 'inherit');
		$(list).css('bottom', 'inherit');

		var parentList = $(list).parents('.default-list').first();
		$(parentList).css('overflow', 'visible');

		var left = $(dropdown).hasClass('outside') ? dropdownPos.left + $(dropdown).innerWidth() : dropdownPos.left;

		$( list ).css('left', left+'px');
		$( list ).css('top', dropdownPos.top+'px');


		var inView = mfElement.isInViewport(list);

		if( !inView.right ) {
			if( $(dropdown).hasClass('outside') ) {
				$( list ).css('left', (dropdownPos.left - $(list).innerWidth())+'px');
			} else {
				$( list ).css('left', (dropdownPos.left + $(dropdown).innerWidth() - $(list).innerWidth())+'px');
			}
		}

		if( !inView.bottom ) {

			$(list).css('max-height', '50vh');
			$(list).css('overflow', 'hidden');
			$(list).css('overflow-y', 'scroll');

			inView = mfElement.isInViewport(list);
			if( !inView.bottom ) {
				$(list).css('bottom', '0');
				$(list).css('top', 'auto');
			}
		}
	}

	/**
	 * DROPDOWN
	 */
	body.on('click', '.dropdown', function (e) {
		var ul = $(this).children('ul').first();

		// console.log($(this).hasClass('disabled'));
		// normal dropdown
		if (!$(this).hasClass('disabled') && !$(this).hasClass('fixed')) {
			mfElement.moveElementInViewport(ul);
			$(ul).fadeToggle('fast');

			//position fixed for overflow hidden/scroll container
		} else if (!$(this).hasClass('disabled') && $(this).hasClass('fixed')) {
			addFixedProperties(this, ul, e);
			$(ul).fadeToggle('fast');
		}
	});


	body.on('mousemove', '.dropdown', function (e) {

		var ul = $(this).children('ul').first();

		if (!$(ul).is(":visible")) {
			if (!$(this).hasClass('fixed') && !$(this).children('.dropdown-btn').first().length && !$(this).hasClass('disabled')) {
				mfElement.moveElementInViewport(ul);
				$(ul).fadeIn('fast');

				//position fixed for overflow hidden/scroll container
			} else if ($(this).hasClass('fixed') && !$(this).children('.dropdown-btn').first().length && !$(this).hasClass('disabled')) {
				addFixedProperties(this, ul, e);
				$(ul).fadeIn('fast');
			}
		}

	});

	body.on('mouseout', '.dropdown', function (event) {
		var e = event.toElement || event.relatedTarget;
		if (!mfElement.isDescendant(this, e)) {
			var ul = $(this).children('ul').first();

			$(ul).hide();
		}
	});

})(jQuery);