;
(function($) {
	$.fn.sectionToggle = function(sections, options){
		var opts = $.extend({}, $.fn.sectionToggle.defaults, options),
		$sections;
		
		if (sections.hasOwnProperty('jquery')) {
			$sections = sections;
		} else {
			$sections = $(sections);
		}
		
		this.eq(0).parent().addClass(opts.bottomSectionClass);
		
		return this.each(function(index) {
			var $this = $(this),
			$sects = $sections;
			
			if ( !$sects[index] ) {
				return;
			}
			$this.data( '$sect', $sects.eq(index) );
			
			$this
				.append('<div>')
				.append('<div>')
				.append('<div>')
				.children()
					.first()
						.css({ position: 'absolute' })
						.addClass( opts.handleClass )
						.draggable({
							axis: 'y',
							containment: 'parent',
							stop: finishTravel
						})
						.text(index)
						.end()
					.slice(1)
						.css({ height: '50%' })
						.droppable({
							hoverClass: 'dropped',
							drop: toggleSection
						})
						.end()
					.slice(2)
						.addClass('sectionToggle-drop-on')
						.end()
					.end();
		});
		
		
		function finishTravel(e, ui) {
			var dHeight = $(e.target).outerHeight(),
			top = e.target.offsetTop,
			pHeight = $(e.target.offsetParent).height();
			
			if (2*top + dHeight >= pHeight) {
				$(e.target).animate({top:(pHeight/2)}, 100);
			} else {
				$(e.target).animate({top:0}, 100);
			}
		}
		
		
		function toggleSection(e, ui) {
			var $target = $(e.target),
			$sect = $target.parent().data('$sect'),
			bID = 'sectionToggle-section-bottom',
			bClass = opts.bottomSectionClass;
			
			if ( $target.hasClass('sectionToggle-drop-on') ) {
				if ( !$sect.nextAll().is('#'+bID) ) {
					$('#'+bID).removeAttr('id');
					$('.'+bClass).removeClass(bClass);
					$sect.attr('id', bID)
					.addClass(bClass);
				}
				$sect.slideDown(200);
			} else {
				$sect.slideUp(200, function() {
					if ( $sect.attr('id') === bID ) {
						$sect
							.removeAttr('id')
							.removeClass(bClass)
							.prevAll(':not(:hidden)')
								.last()
									.attr('id', bID)
									.addClass(bClass);
					}
				});
			}
		}
	};
	
	$.fn.sectionToggle.defaults = {
		handleClass: 'ui-border-radius-tl',
		activeClass: '',
		hoverClass: '',
		bottomSectionClass: 'ui-border-radius-bottom',
		appendCloseSectLink: true
	};
})(jQuery);
