/**************************************
Dropdown

Makes a dropdown menu from a block of content.


Options:
type 		- Sets type of interaction ('click' or 'hover')
trigger 	- Selector for elements OUTSIDE dropdown which cause it to toggle
close 		- Selector for elements INSIDE dropdown which cause it to close
**************************************/

(function($){

	$.fn.dropdown = function(opts) {
		
		opts = $.extend({
			type:		'click',
			trigger:	null,
			close:		null,
			speed:		'fast',
			transition:	'slide'
		},opts);
		
		return $(this).each(function(){
		
			var $this = $(this),
				$triggers = $(opts.trigger),
				$close = $this.find(opts.close),
				isOpen,
				isHover,
				timer;
			
			$this.bind('dropdown.open',_open)
					.bind('dropdown.close',_close)
					.bind('dropdown.toggle',_toggle)
					.trigger('dropdown.close',true);
			
			if($.browser.msie && $.browser.version < 7) {
				$this.show();
				var $iframe = $('<iframe></iframe>')
						.addClass('dropdown')
						.css({
							 opacity:0,
							 width:$this.width(),
							 height:$this.height()
						});
						
				$iframe.insertBefore($this);
				$this = $this.add($iframe).hide();
			}
			
			switch(opts.type) {
				case 'click':
					$triggers.click(function(e){
						setTimeout(function(){$this.trigger('dropdown.toggle');});
						e.preventDefault();
					});
					$close.click(function(){
						$this.trigger('dropdown.close');
					});
					$this.click(function(){
						return false;
					});
					$(document).click(function(){
						$this.trigger('dropdown.close');
					});
					break;
				case 'hover':
					var f = function(){
							$this.trigger('dropdown.open');
							clearTimeout(timer);
							isHover = true;
						},
						g = function(){
							timer = setTimeout(function(){if(!isHover) $this.trigger('dropdown.close');},100);
							isHover = false;
						}
					$triggers.hover(f,g);
					$this.hover(f,g);
					break;
			}
			
			function _open() {
				$('#destinationOverlayHeading').attr("role", "alert").focus();				
				isOpen = true;
				switch(opts.transition) {
					case 'slide':
						$this.slideDown(opts.speed);
						break;
					default:
						$this.show();
				}
				
			}
			
			function _close(e,snap) {
				isOpen = false;
				if(snap) {
					$this.hide();
				}
				else {
					switch(opts.transition) {
						case 'slide':
							$this.slideUp(opts.speed);
							break;
						default:
							$this.hide();
					}
				}
			}
			
			function _toggle() {
				isOpen?_close():_open();
			}
			
		});
		
	}

})(jQuery);
