(function(ui) {
	var TEXT_INPUT_TYPES = $.w('color date datetime datetime-local email file month number password range search tel text time url week'),
		COUNTRIES_THAT_REQUIRE_STATE = $.w('US CA'),
		SCROLL_TO_SPEED = 500;

	// Public
	ui.init = function() {
		initFocusClasses();
		initTopNavigation();
		initSideNavigation();
		initParentSelecting();
		initInternationalFields();
		initScrollTo();
		initHoverToggles();
		initHoverable();
		
		if (!Modernizr.input.placeholder) { initPlaceholders(); }
		if (!Modernizr.input.autofocus) { initAutofocus(); }

		if ($.browser.msie && $.browser.version < 7) {
			attachHidingSelectsOnOverlay();
		}
	};

	// Private
	function attachHidingSelectsOnOverlay() {
		$(document)
			.bind('overlay.on', function() {
				$('select')
					.each(function() {
						var $this = $(this);
						$this.data('overlayVisible', $this.is(':visible'));
					})
					.hide();
			})
			.bind('overlay.off', function() {
				$('select')
					.filter(function() { return $(this).data('overlayVisible'); })
					.show();
			});
	}

	function initFocusClasses() {
		var inputTypesSelectors = $.map(TEXT_INPUT_TYPES, function(n) { return 'input[type=' + n + ']'; });
		$($.flatten([inputTypesSelectors, 'textarea']).join())
			.live('focusin', function() { $(this).addClass('focused'); })
			.live('focusout', function() { $(this).removeClass('focused'); });
	}

	function initPlaceholders() {
		function setPlaceholder() {
			var $this = $(this);
			if (!$this.val()) { $this.val($this.attr('placeholder')); }
		}

		$('input[placeholder]')
			.live('focusin', function() { $(this).val(''); })
			.live('focusout', setPlaceholder)
			.each(setPlaceholder);
	}
	
	function initAutofocus () {
		$('input[autofocus]:first').focus();
	}

	function initTopNavigation() {
		var menuTimer = null;

		function addHover() {
			var $that = $(this);
			menuTimer = menuTimer || setTimeout(function() { $that.addClass('hover'); }, 100);

			$(document).trigger('overlay.on');
		}

		function removeHover() {
			clearTimeout(menuTimer);
			menuTimer = null;

			$(this).removeClass('hover');
			$(document).trigger('overlay.off');
		}

		$('#nav-primary')
			.find('li:has(ul)')
				.hover(addHover, removeHover)
					.filter(function() {
						return $(this).offset().left > ($(window).width() / 2);
					})
						.addClass('altdrop')
						.end()
					.end()
			.find('> li a')
				.focusin(function() { addHover.apply($(this).closest('li')); })
				.focusout(function() { removeHover.apply($(this).closest('li')); });
	}

	function initSideNavigation() {
		$('div.collapse-menu').each(function() {
			var $menu = $(this),
				metadata = $menu.metadata().collapse || { max: 6 };

			if ($menu.find('> ul > li').length > metadata.max) {
				WEBLINC.templates
					.render('sideNavgiationViewAllLink')
						.appendTo($menu.find('> ul:first'))
						.find('a')
							.click(function(e) {
								e.preventDefault();

								$(this).text(function(i, current) {
									return current === '> View All' ? '> Hide' : '> View All';
								});

								$menu.find('> ul > li:gt(' + (metadata.max - 1) + '):not(.list-toggle)').toggle();
							})
							.click();
			}
		});
	}
	
	function initParentSelecting() {
		$('.parent-select').live('click', function(e) {
			e.preventDefault();
			$(this).parent().addClass('selected').siblings().removeClass('selected');
		});
	}
	
	function initInternationalFields() {
		$('select[name=country]')
        	.change(function() {
        		var $this = $(this),
        			$form = $this.closest('form'),
        			$select = $form.find('li.state-pairing'),
        			$text = $form.find('li.freetextstate-pairing');

        		if ($.inArray($this.val(), COUNTRIES_THAT_REQUIRE_STATE) >= 0) {
        			$text.hide();
        			$select.show();
        		}
        		else {
        			$select.hide();
        			$text.show();
        		}
        	})
        	.trigger('change');
	}

	function initScrollTo() {
		$('.scroll-to').live('click', function(e) {
			var $this = $(this),
				destination = $this.metadata()['scroll-to'];
				
			if (!destination && $this.is('a') && $($this.attr('href')).length) { 
				destination = $this.attr('href');
			}
				
			if (destination) {
				e.preventDefault();
				$(document).scrollTo(destination, SCROLL_TO_SPEED, function() { 
					$this.trigger('scrolled');
				});
			}
		});
	}

	function initHoverable() {
		var $hoverable = $('.hoverable');
		$hoverable.hoverIntent({
			timeout: 0,
			over:function(){
				$(this).addClass('hover');
			},
			out: function(){
				$(this).removeClass('hover');
			}
		});
	}

	function initHoverToggles() {
		$('.hover-toggle').hover(
			function() { $(this).find('.hover-toggled').show(); },
			function() { $(this).find('.hover-toggled').hide(); }
		);
	}
})($.namespace('WEBLINC.ui'));
