/** 
 * Dynamic Link Select Box
 * 
 * Copyright (c) 2009 init AG
 *   http://www.init.de
 *
 */

(function($) {
	$.fn.linkselect = function() {
	
	
		this.each( function(a) {
	        var initialSelection = $(this).children("li:first").html();
			var menuId = $(this).id + "_mod";
			var menuItemId = menuId + "_item";
			
			var menuHtml = 	'<div id="' + menuId + '" class="dropdown cf" tabindex="0">' + "\n" +
  						'	<div class="arrow">' + "\n" +
    					'		<div class="list">' + "\n" +
      					'			<p>' + initialSelection + '</p>' + "\n" +
						'		</div>' + "\n" +
						'	</div>' + "\n" +
						'</div>';
			var menuItemHtml = '<div id="' + menuItemId + '" class="dropdownitem" style="display: none">' + "\n";
			var i = 0;
			$(this).children().each(function() {
				// e.g. <p id="id_value">value</p>
				if(i!=0) {
					menuItemHtml += "<p>" + $(this).html()  + "</p>\n";
				}
				i++;
			});
			menuItemHtml += '</div>';
		
		
			$(this).before(menuHtml + menuItemHtml);
			$(this).hide();
			
			var menuSelector = '#' + menuId;
			var menuItemSelector = '#' + menuItemId;
			

			$(menuSelector).click(function() {
				// show items list
				$(menuItemSelector).toggle();
				// only care when the menu item is visible
				if ($(menuItemSelector).css("display") != "none") {
				
					var offset = $(this).offset();
					//$(menuItemSelector).css("left", offset.left + "px");
					$(menuItemSelector).css("top", offset.top + 19 + "px");
					
					// highlight item list that is currently selected
					var currentText = $(menuSelector + ' p').text();
					$(menuItemSelector + ' p').each(function() {
						var itemListText = $(this).text(); 
						if (itemListText == currentText) {
							$(this).addClass("selected");
						}
					});
				} 
			});			

		});
	
	
	
	
	}
})(jQuery);

$(document).ready(function() {

	//Selectbox
	if($('#selectBoxModule').is("ul")) {
		$('#selectBoxModule').linkselect();
	}

});