$(document).ready(function() {
	
	getResults();
	
	for (i=0;i<=3;i++)
	{
		createDropDown(i);
	}	
		$(".dropdown dt a").click(function() {
			
			//alert($(this).parents("div").attr('id'));
			//alert($(this).parent().next().children().attr('tagName'));
			$($(this).parent().next().children()).toggle();
			return (false);
		});

		$(document).bind('click', function(e) {
			var $clicked = $(e.target);
			if (! $clicked.parents().hasClass("dropdown"))
				$(".dropdown dd ul").hide();
		});
					
		$(".dropdown dd ul li a").click(function() {
			
			var text = $(this).html();
			//alert($(this).children().html());
			$($(this).parents("dl").children("dt").children("a")).html(text);
			$(".dropdown dd ul").hide();
			var source = $($(this).parents("h2").children("select"));
			source.val($(this).find("span.value").html())
			getResults();
			return (false);
		});
	
});

function createDropDown(x){
	var source = $("select:eq("+x+")");
	var selected = source.find("option[selected]");
	var options = $("option", source);
	$("select:eq("+x+")").hide();
	
	$(".courseCategory h2:eq("+x+")").append('<dl id="target" class="dropdown"></dl>')
	$(".dropdown:eq("+x+")").append('<dt><a href="#">' + selected.text() + 
		'<span class="value">' + selected.val() + 
		'</span></a></dt>')
	$(".dropdown:eq("+x+")").append('<dd><ul></ul></dd>')

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

function getResults(){
var disc = document.getElementById("discipline")
var a = disc.selectedIndex
var sendDisc = disc.options[a].value

var dur = document.getElementById("duration")
var b = dur.selectedIndex
var sendDur = dur.options[b].value

var dest = document.getElementById("destination")
var c = dest.selectedIndex
var sendDest = dest.options[c].value

var div = document.getElementById("division")
var d = div.selectedIndex
var sendDiv = div.options[d].value

var xmlhttp;
if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				document.getElementById("getCourses").innerHTML=xmlhttp.responseText;
				//document.getElementById("getURL").innerHTML="courses.php?disc="+sendDisc+"&dur="+sendDur+"&dest="+sendDest+"&div="+sendDiv;
			}
	}
xmlhttp.open("GET","/wp-content/themes/peak_leaders/includes/courses.php?disc="+sendDisc+"&dur="+sendDur+"&dest="+sendDest+"&div="+sendDiv,true);
xmlhttp.send();
}
