$(document).ready(function() {
	
	selectBox = $('#location'),
	children = selectBox.children();
	
	// Hide the <select> and append the <div> for the dropdown
	selectBox.before('<div id="selectBox" tabindex="4"><span></span><div></div></div>');
	selectBox.hide();
	
	var dropDown = $('#selectBox'),
	list = dropDown.find('div').hide(),
	currItem = dropDown.find(':first');
	
	// Change the color on focus
	dropDown.focus(function() {
		$(this).css('background-color', '#f9ffbb');
	}).focusout(function() {
		$(this).css('background-color', '#fff');
		list.slideUp();
	}).blur(function() {
		$(this).css('background-color', '#fff');
		list.slideUp();
	});
	
	var text, val
	// Add the items to the <div>
	children.each(function(index) {
		text = $(this).text();
		val = $(this).val();
		
		// Set the currently selected item
		// from the <select>
		if ($(this).attr('selected')) {
			currItem.append('<a href="javascript:void(0);" rel="' + val + '">' + text + '</a>');
		}
		// Append all <option>'s to the <div>
		list.append('<a href="javascript:void(0);" rel="' + val + '">' + text + '</a>');
	});
	
	var selected = currItem.find('a');
	
	// Hide the dropdown if the current item
	// is clicked again
	selected.click(function() {
		if (list.is(':hidden')) {
			list.slideDown(300);
		} else {
			list.slideUp(300);
		}
	});
	
	var opts = list.children();
	
	// Bind a click function to all the items
	// in the dropdown
	opts.each(function() {
		$(this).click(function() {
			// Select the <option> in the <select>
			$('#location option[value=' + $(this).attr('rel') + ']').attr('selected', 'selected');
			
			// Change the text and rel scope of the <a>
			selected.text($(this).text());
			selected.attr('rel', $(this).attr('rel'));
			
			list.slideUp(300);
		});
	});
	
});
