$(document).ready(function(){
	/* unique function from http://www.webdeveloper.com/forum/showthread.php?t=215646 */
	/* extends the functionality of Arrays to return only unique elements */
	Array.prototype.unique = function(){
			var vals = this;
			var uniques = [];
			for(var i=vals.length;i--;){
				var val = vals[i];  
				if($.inArray( val, uniques )===-1){
				uniques.unshift(val);
				}
			}
			return uniques;
			} 
	if ($('#rcal').length) { // only run this if we're on the rolling calendar page
		/* prepares the form and drop down menu */
		$('<form id="location-filter"></form>').insertAfter('h1');
		$('#location-filter').append('<label for="filters">Show events in </label>');
		$('#location-filter').append('<select id="filters"></select>');
		$('#filters').append('<option id="all-locations">all locations</option>');
		$('#filters').append('<optgroup id="International" label="International"></optgroup>');
	
		// build the location array
		var locations = new Array();
		$('.events-listing li').each(function(i){
			var tString = $(this).attr('title');
			locations[i] = tString;
		});
		locations = locations.unique();
		locations.sort();
		
		/*$.unique(locations);*/
		var clength = locations.length;
	
		// add the locations to the select element
		var n=0;
		for (n=0;n<clength;n++) {
			var location = locations[n];
			if((location != "Victoria") && (location != "Australia")){
				$('#International').append('<option>'+location+'</option>');
			} else {
				$('<option>'+location+'</option>').insertAfter('#all-locations');
			};
		}
	
		// handle any changes to the select element
		$('#filters').change(function () {
			var filter = '';
			$('#filters option:selected').each(function () {
				filter += $(this).text();
			});
			$(".events-listing, .events-listing li, #main-content h3").hide();
			if(filter!='all locations'){ // only show the relevant ones
				$("li[title="+filter+"]").parent().prev().fadeIn('slow');
				$("li[title="+filter+"]").show();
				$("li[title="+filter+"]").parent().fadeIn('slow');
			} else { // reset
				$("ul:has(li)").show();
				$("ul:has(li) li").show();
				$("ul:has(li)").prev().show();
			};
		})
		
		// reset on load
		.change();
	};


	// on the create event form we want to copy the value from the select field into a text input

	$('#location').bind('ready change click keyup', function() {
	  $('#metadata_field_text_494175_value').val($(this).find("option:selected").html());
	});



       // change unordered lists of this class into an instant pulldown

$('ul.selectdropdown').each(function(){
  var list=$(this),
  select=$(document.createElement('select')).insertBefore($(this).hide());
  $('>li a', this).each(function(){
    var target=$(this).attr('target'),
    option=$(document.createElement('option'))
     .appendTo(select)
     .val(this.href)
     .html($(this).html())
     .click(function(){
         window.location.href=$(this).val();
      });
  });
  list.remove();
});

});





