/// <reference path="../../../vendor/jquery/jquery-1.3.2.custom.js"/>

jQuery.makeDropDown = function(link, contents, options)
{
	var timeout = null;
	var defaultOptions = {
		allowMultiSelect: false,
		slideSpeed: 200,
		contentsClass: "dropDownContents",
		bindevent: "click"
	};
	var $options = $.extend({},defaultOptions, options);

	var $contentsContainer = $(document.createElement("div"));
	$contentsContainer.addClass($options.contentsClass);
	$contentsContainer.hide();
	$contentsContainer.css("position", "absolute");
	$contentsContainer.append(contents);
	var $link = $(link);
	
	//create a container object that we can use to trap the hover status of both the link and the dropDown
	
	$link.parent().append($contentsContainer);
	link.HideDropDown = hideDropDownNow;
	link.ShowDropDown = showDropDown;
	link.CancelHide = cancelHide;
	link.IsDropDownVisible = isDropDownVisible;	
	$link.bind($options.bindevent, ($options.clickFn) ? $options.clickFn : function() {});

	// Hide the dropdown when the user clicks somewhere that's both outside the link and the dropdown.
	// We do this rather than detecting focus changes because if the dropdown has a scrollbar, we can't
	// tell the difference between focus moving to the scrollbar and focus moving to something else on
	// the page.
	$(document).click(function (event)
	{
		if (isDropDownVisible())
		{
			var contentsPos = $contentsContainer.offset()
			var inputPos = $link.offset();
			
			// Outs the bounds of the text box and dropdown contents?
			if (!pointIsInRect(event.pageX, event.pageY,  inputPos.left, inputPos.top,  $link.outerWidth(), $link.outerHeight())
			 && !pointIsInRect(event.pageX, event.pageY,  contentsPos.left, contentsPos.top,  $contentsContainer.outerWidth(), $contentsContainer.outerHeight()))
			{
				hideDropDown();
			}
		}
	});
	
	function showDropDown()
	{
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = $link.position();
		// reposition
		$contentsContainer.css({
			top: (pos.top + $link.outerHeight()) + "px",
			left: pos.left + "px"
		}).show();
	}
	
	function hideDropDown()
	{
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideDropDownNow, 200);
	}
	
	function cancelHide()
	{
		if (timeout)
			clearTimeout(timeout);
	}
	
	function hideDropDownNow()
	{
		if (timeout)
			clearTimeout(timeout);
		
		if (isDropDownVisible)
		{
			$contentsContainer.hide();
			if ($.isFunction(options.hideDropDownCallback))
				options.hideDropDownCallback();
		}
	}

	function isDropDownVisible()
	{
		return $contentsContainer.is(":visible");
	}
}

jQuery.fn.makeDropDown = function(contents, options)
{
	this.each(function() {
		new jQuery.makeDropDown(this, contents, options);
	});
	return this;
}




