/* --------------------------------------------------------------------
	Branche selector
-------------------------------------------------------------------- */

$(document).ready(function() {
	
	if ( $('#brancheSelector').length < 1 ) return; 

	brancheSelector();
	
	function brancheSelector() {
		$brancheSelector = $('#brancheSelector');
		$brancheBox = $('#brancheSelector .selector .header');
		$brancheBtn = $('#brancheSelector .selector > p').eq(0);
		var timer;
		
		$("a", $brancheBtn).remove();
		$("span", $brancheBtn).show();
	
		$brancheSelector.mouseenter(function() {
			$brancheBox.closest('.block').css('overflow', 'visible');
		});

		// branche button behavior
		$brancheBtn
		.css('cursor', 'pointer')
		.hover(function() {
			$brancheBtn.addClass('hover');
		}, function() {
			$brancheBtn.removeClass('hover');
		})
		.click(function(event) {
			if ( $brancheBox.is(':visible') ) {
				$brancheBox.closest('.block').css('overflow', 'hidden');
				$brancheBox.hide();
			} else {
				brancheBoxPositioner();
				$brancheBox.show();
			}
			event.stopPropagation();
		});
		
		// hide the branchebox when not used
		$brancheBox
		.mouseleave(function() {
			timer = setTimeout(function () {
				$brancheBox.closest('.block').css('overflow', 'hidden');
				$brancheBox.hide();
			}, 500);
		}).mouseenter(function() {
			clearTimeout(timer);
		});
		
		// position the branch box on top off the buttom
		function brancheBoxPositioner() {
			// make the branche selectbox viewable for calculating the offset position
			$brancheBox.css('visibility', 'hidden').show();
			
			// position the branche selectbox
			var t = ($brancheBox.outerHeight() - $brancheBtn.outerHeight() - 15) / 2;
			$brancheBox.css('top', '-' + t + 'px');
			
			// correct the position when branche selectbox makes the page longer
			var brancheBoxBottom = $brancheBox.outerHeight() + $brancheBox.offset().top;
			var containerBottom = $('#container').outerHeight() + $('#container').offset().top;
			
			if (brancheBoxBottom > containerBottom) {
				t += brancheBoxBottom - containerBottom - 15;
				$brancheBox.css('top', '-' + t + 'px');
			};
			
			// popout to the right or to the left?
			if ($brancheSelector.offset().left - $('#container').offset().left > 600) {
				$brancheSelector.addClass('rightCol');
			}
			
			// show the branche selectbox when calculating the offset position is finished
			$brancheBox.hide().css('visibility', 'visible');
		};
	};

});
