$(document).ready(function(){
	
	$("#featured .slideshow").mslide();
	
	$(".cycle").cycle({});
	
	// datepicker and filter events
	
	if ($('#datefilter').length) {

		var filterEvents = function() {
			var from = $('#datefilter .from').val();
			var to   = $('#datefilter .to').val();
			$('div.eventlist').each(function() {
				var isVisible = $(this).data('event-to') >= from && $(this).data('event-from') <= to;
				$(this).toggle(isVisible);
			});
		}

		// set data attributes
		$('div.eventlist').each(function() {
			var _parts = this.id.match(/^event-from-(.+)-to-(.+)$/);
			$(this).data('event-from', _parts[1]);
			$(this).data('event-to',   _parts[2]);
		});

		// init datepicker
		$('#datefilter .has-datepick').datepick(
			$.extend({
				showTrigger: '#calImg',
				showAnim: ''
			},
	    	$.datepick.regional['sv'])
		);
		
		// filter events and handle min/max dates
		$('#datefilter .from').datepick('option', 'onSelect', function(dates) {
			$('#datefilter .to').datepick('option', 'minDate', dates[0] || null); 
			filterEvents();
		});

		$('#datefilter .to').datepick('option', 'onSelect', function(dates) {
			$('#datefilter .from').datepick('option', 'maxDate', dates[0] || null); 
			filterEvents();
		});

		$('#datefilter .to').datepick('option', 'minDate', $('#datefilter .from').datepick('getDate')[0]); 
		$('#datefilter .from').datepick('option', 'maxDate', $('#datefilter .to').datepick('getDate')[0]); 

		// filter direktly ..
		filterEvents();
		
		// .. and after keyup as well (probably not necessary since datepick handles this)
		$('#datefilter input').keyup(filterEvents);

	}
	
	// google maps
	
	if ($('#map-controller option').length) {
	
		var myOptions = {
			mapTypeControl: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			streetViewControl: false,
			zoom: 14
		};
		var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
	
		var asLatLng = function(data) {
			_d = data.split(',');
			return new google.maps.LatLng(_d[0], _d[1]);
		}
	
		var setCenter = function(data) {
			map.setCenter(asLatLng(data));
		}
	
		var addMarker = function(data) {
			new google.maps.Marker({
				position: asLatLng(data), 
				map: map
			});
		}

		$('#map-controller option').each(function() {
			addMarker(this.value);
		});
	
		$('#map-controller').change(function() {
			setCenter(this.value);
		});

		setCenter($('#map-controller option:selected').val());
		
	}
	
	// IE7 layout fix


	if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
		$('.eventlist.first-cell').each(function() {
			var next = $(this).next('.eventlist');
			if (next.length) {
				var h = Math.max($(this).height(), next.height());
				$(this).height(h);
				next.height(h);
			}
		});
	}

});

