$(document).ready(function() {

	initCustomSelects();
	$(".customSelect").hide();
	
});

function initCustomSelects(id) {	

	if(!id) {
		$(".customSelect").each(function() {															
			originalID = $(this)[0].id;		
			$("#" + originalID + "_value").remove();			
			$($(this)[0].parentNode.parentNode).append("<input type='hidden' name='" + originalID + "_value' id='" + originalID + "_value' value='" + $(this).val() + "'>");		
			createDropDown(originalID);
		});
	} else {
		originalID = $("#" + id)[0].id;												
		$("#" + originalID + "_value").remove();		
		$($("#" + id)[0].parentNode.parentNode).append("<input type='hidden' name='" + originalID + "_value' id='" + originalID + "_value' value='" + $(this).val() + "'>");		
		createDropDown(originalID);
	}
	
	$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("dropdown")) {
			$(".dropdown dd ul").hide();
		}
	});
	
	$(".dropdown dt a").click(function() {		
		// get status
		currentStatus = $($(this)[0].parentNode.parentNode).find("ul")[0].style.display;
		//alert(currentStatus);
		
		// hide all the menus
		$(".dropdown dd ul").hide();
		$($(this)[0].parentNode.parentNode).find("ul").toggle();
		
		// based on the status before click - hide or show
		/*
		if(currentStatus!="block") {
			$($(this)[0].parentNode.parentNode).find("ul").show();														  
		} else {
			$($(this)[0].parentNode.parentNode).find("ul").hide();  
		}
		*/
	});
	
	$(".dropdown dd ul li a").click(function() {
		var text = $(this).html();
		$($(this)[0].parentNode.parentNode.parentNode.parentNode).find(".selectValue").html(text);
		$(".dropdown dd ul").hide();
		
		matchingSelect = $($(this)[0].parentNode.parentNode.parentNode.parentNode)[0].id.replace("target_","");
		matchingSelect = matchingSelect.replace("target_","");		

		$("#" + matchingSelect + "_value").val($(this).find(".value").html());
		$("#" + matchingSelect).val($(this).find(".value").html())
		$("#" + matchingSelect).trigger("onchange");
	
	});
}
 
function createDropDown(id){
	
	var parent = $("#" + id).parent();
	var source = $("#" + id);

	var selected = source.find("option[selected]");
	var options = $("option", source);
	
	$("#target_" + id).remove();
		
	$(parent).append('<dl id="target_' + id +'" class="dropdown"></dl>')
	$("#target_" + id).append('<dt><a class="selectValue" href="javascript:;">' + selected.text() + '<span class="value">' + selected.val() + '</span></a></dt>')
	$("#target_" + id).append('<dd><ul></ul></dd>');

	options.each(function(){
		 $("#target_" + id + " dd ul").append('<li><a href="javascript:;">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>');
	});

}
	