$(document).ready(function() {
 	
	/* Content Carousel */
	
	$(".flowpanes.carousel-content").scrollable({ circular: true }).navigator({
		navi: ".flowtabs",
		naviItem: 'a',
		activeClass: 'current',
		history: true
	});
	
	/* Content Carousel controls */
	
	$('.carousel-controls a').mouseover(function() {
		$(this).toggleClass('hover');
	})
	
	$('.carousel-controls a').mouseout(function() {
		$(this).toggleClass('hover');
	})
	
	$('.carousel-controls a').click(function() {
		if(!$('.pointer-fixed', this).length) $(this).prepend('<span class="pointer-fixed"></span>');
	})
	
	/* ticker */

	$('#ticker ul').innerfade({ speed: 'slow', timeout: 4000, type: 'sequence', containerheight: '20px' });
	
	/* partners carousel */
	
	if ($(".carousel-partners").length) {
	
		$(".carousel-partners .item").each(function() {
		
			$('a:last', this).addClass('last')
		
		});
	
		if ($(".carousel-partners .item").length > 1) {
		
			$(".carousel-partners .flowpanes").scrollable({ circular: true }).navigator({
				navi: ".flowtabs",
				naviItem: 'a',
				activeClass: 'current'
			});
		
		} else {
		
			$('.partner-carousel-controls').remove();
		
		}
	
	};
	
	
	/* Masthead carousel */
	
	//$('#masthead-carousel').scrollable({ circular: true });
	
	var masthead_carousel_total = $('#masthead-carousel .controls a').length;
	
	if (masthead_carousel_total > 1) {
		
		var wrap = $("#image-wrap");
		wrap.append('<img class="loaded-image not-shown" />')
	
		$('#masthead-carousel .controls a').click(function() {

			var url = $(this).attr("href");
			
			wrap.stop();
			
			// cache the image
			$('#masthead-carousel .loaded-image').attr('src', url);
			
			// fade
			wrap.fadeOut("slow", function() {
				
				// load the src in the containing img when ready
				$('#masthead-carousel .loaded-image').ready(function() {
					
					wrap.fadeIn("slow");
					wrap.find("img").attr("src", url);
				})
				
			});
			
			return false;

		});
		
	};
	
	if ($('#carousel-gallery').length > 0) {
					
		$("#carousel-gallery .flowpanes")
			.scrollable({ 
				circular: true
			})
			// .navigator({
			// 				navi: ".flowtabs",
			// 				navItem: "a",
			// 				activeClass: 'current'
			// 			});
		
	};
	
	
	/* Masthead gallery */
		
	if ($("#carousel-gallery").length) {
	
		$(".flowpanes").scrollable({ 
				circular: true
			})
		
		$(".flowpanes").navigator({
				navi: ".flowtabs",
				navItem: "a",
				activeClass: 'current'
			});
		
	};
	
	if ($(".masthead-gallery").length) {
		
		var masthead_gal_active = false;
		var masthead_gal_current = 0;
		
		setTimeout(function() {
			if (!masthead_gal_active) $(".masthead-gallery .close-icon").click();
		}, 5000);
		
		$(".masthead-gallery .next-icon").click(function() {										
			var index = (masthead_gal_current < $(".masthead-gallery .thumbs a").length-1) ? masthead_gal_current+1 : 0;
			var href = $(".masthead-gallery .thumbs a:eq("+index+")").attr('rel');
			masthead_gal_current = index;						
			$('.masthead-gallery .gallery .image').attr('src', href);
			return false;
		})
		
		$(".masthead-gallery .prev-icon").click(function() {										
			var index = (masthead_gal_current == 0) ? $(".masthead-gallery .thumbs a").length-1 : masthead_gal_current-1;
			var href = $(".masthead-gallery .thumbs a:eq("+index+")").attr('rel');
			masthead_gal_current = index;						
			$('.masthead-gallery .gallery .image').attr('src', href);
			return false;
		})
		
		$(".masthead-gallery .close-icon").click(function() {
			
			masthead_gal_active = true;
			
			var container = $('#masthead-info-block');
			
			$(container).css({overflow: 'hidden'});
			
			$('.thumbs', container).animate({opacity: 0}, 300, function() {
				$(container).animate({width: 40 }, 500, function() {
					$('.masthead-gallery .icon').show().css({opacity : 0}).animate({opacity: 1}, 300);
				});
			});
			
			$(this).hide();
			
			return false;
		})
		
		$('.gallery-icon').click(function() {
			
			var container = $('#masthead-info-block');
			
			$('.masthead-gallery .icon').animate({opacity: 0}, 300, function() {
				$(this).hide().css({opacity : 1});
				$('.close-icon').show();
			});
			$(container).animate({width: 304 }, 500, function() {
				$('.thumbs', container).animate({opacity: 1}, 300);
			});
			
			return false;
			
		})
	
		$(".masthead-gallery .thumbs a").click(function() {
			
			var href = $(this).attr('rel');
			
			$('.masthead-gallery .gallery .image').attr('src', href);
			
			return false;
		})
		
	};
	
	
	
	
	/* hospitality panels */
	
	$('.landing-panels .panel:not(:first)').hide();
	
	var myFile = document.location.toString();
	
	if (myFile.match('#')) 
	{
		var anchor = '#' + myFile.split('#')[1];
		
		$('.landing-panels .panel').hide();
		$(anchor).show();
		
		$.scrollTo($(anchor), 500);
	}
	
	$('.landing-button a, .promo-group h2 a').click(function() {
		
		var anchor = $(this).attr('href');
				
		if (anchor.indexOf('#') == 0) {
			
			$('.landing-panels .panel').hide();
			
			$(anchor).show();
			
			$.scrollTo($(anchor), 500);

			return false;
			
		}
			
	})
	
	
	/* Tour room selector Carousel */
	
	if ($(".carousel-tour-rooms").length) {
	
		$(".carousel-tour-rooms .flowpanes")
			.scrollable({ 
				circular: false
			})
			.navigator({
				navi: ".flowtabs",
				navItem: "a",
				activeClass: 'current'
			});
			
		$(".carousel-tour-rooms .item a").hover(
			
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			})
		
	};
	
	
	/* Tour tooltips */
	
	var hotspot_offet = 25;
	var tooltips = $('.tour-tooltip');
	var tooltip_status = false;
	var tooltip_index = 100;
	
	// add highlight html
	$('#tour .hotspot').each(function() {
		$(this).append('<div class="highlight"></div>')
	})
	
	// toolbar link options
	
	$('#highlight-hotspots').click(function() {

		$('.pane-carousel').fadeOut(300, function() {
			$('#tour-drawer').animate('.state-toolbar', function() {
				
				$('.hotspot .highlight')
					.stop()
					.css({visibility : 'visible'})
				
				if (!$.browser.msie) {
					$('.hotspot .highlight').animate({opacity : 0}, 2000, function() {
						$(this).css({visibility : 'hidden', opacity : 1})
					});
				} else {
					$('.hotspot .highlight').show();
					setTimeout(function() {
						$('.hotspot .highlight').hide();
					},2000)
				}
				
				$('.hotspot .highlight')
					
					
			});
			$('.pane-toolbar').fadeIn(300);
		});
		
		$('#collapse-draw').hide();
		$('#view-more-rooms').show();
		
		return false;
	})
	
	$('#view-more-rooms').click(function() {
		
		$('#tour-drawer').animate('.state-carousel', function() {
			$('.pane-toolbar').hide();
			$('.pane-carousel').fadeIn(300);
			//$('.pane-carousel h2').show();
		});
		$(this).hide();
		$('#collapse-draw').show();	
					
		$('#t1').parent().addClass('current');
				
		return false;
	})
	
	$('#collapse-draw').click(function() {
		
		$('.pane-carousel').fadeOut(300, function() {
			$('#tour-drawer').animate('.state-toolbar');
			$('.pane-toolbar').fadeIn(300);
		});
		
		$(this).hide();
		$('#view-more-rooms').show();				
		
		return false;
	})
	
	$('.show-item-details').click(function() {
		
		var panel = $('#'+$(this).parents('.tour-tooltip').attr('id')+'-panel');
		
		loadItemDetail(panel);
		
		loadItemGallery(panel);
		
		return false;
	})
	
	$('#page-tour .info-box .button.open-panel a').click(function() {				
		
		var panel = '#' + $(this).attr('rel') + '-panel';
		
		loadItemDetail(panel);
		
		loadItemGallery(panel);
		
		$.scrollTo($('body'), 500);
		
		return false;
	})
	
	$('.back-to-room').click(function() {
		
		$('.pane-item').fadeOut(300, function() {
			$('#tour-drawer').animate('.state-toolbar', function () {
				$('.pane-toolbar, #drawer-links, .pane-hotspots').fadeIn(300);
			});
		});
		
		return false;
	})

	
	// show / hide the tooltips
	$('#tour .hotspot').mouseover(function() {
		
		var padding = 50;
		var x = parseInt($(this).css('left'));
		var y = parseInt($(this).css('top'));
		var tooltip = $("#"+$(this).attr('rel'));
		var tooltip_offset_y = (y < $(tooltip).height()+padding) ? 0-(hotspot_offet*2.3) : ($(tooltip).height()+hotspot_offet);
		var tooltip_offset_x = (x > 800) ? ($(tooltip).width()-hotspot_offet*2.2) : hotspot_offet;
		
		
		if (y < ($(tooltip).height()+padding)) {
			$('.point', tooltip).addClass('top');
		} else {
			$('.point', tooltip).addClass('bottom');
		}
		
		if (x > 800 ) {
			$('.point', tooltip).addClass('right');
		}
		
		tooltip_status = true;
				
		$(tooltip).css({top : (y-tooltip_offset_y), left: (x-tooltip_offset_x)})	
		
		$(tooltip)
			.stop()
			.removeClass('not-shown');
		
		if (!$.browser.msie) $(tooltip).animate({opacity:1});
		else $(tooltip).show();
		
		$(tooltip).css('z-index', tooltip_index);
		
		tooltip_index ++;
		
			
	})
	
	$(tooltips).mouseover(function() {
		tooltip_status = true;
	})
	
	$(tooltips).mouseout(function() {
		tooltip_status = false;
	})
	
	$('#tour .hotspot').mouseout(function() {
		tooltip_status = false;
	})
	
	// handle fading
	if ($('#tour .hotspot').length) {
		
		var tooltip_fade = setInterval(function() {
			
			fadeTooltip();
			
		}, 2000)
		
	};
	
	var inital_width = $('#more-views').width();
	var views_animating = false;
	var views_hover = false;
	
	$('#more-views .link a').click(function() {
		
		if (views_animating) return false;
		
		views_animating = true;
		views_hover = true;
		
		var total = $('#more-views ul li').length;
		var margin = parseFloat($('#more-views ul li').eq(0).css('margin-right'));
		var width = 28; //$('#more-views ul li img').eq(0).attr('width');
		var new_width = inital_width + (total * width) + (total * margin) + 20;
		
		$('#more-views').animate({width: new_width}, 300, function() {
			$('#more-views ul').fadeIn(300, function() {
				views_animating = false;
			});
		})	
		
		return false;
		
	})
	
	$('#more-views').mouseleave(
		function() {
			
			views_hover = false;
			
			if (views_animating) return false;
			
			views_animating = true;
			
			$('#more-views ul').fadeOut(500, function() {
				$('#more-views').animate({width: inital_width}, 500);
				views_animating = false;
				views_hover = false;
			});
			
		}
	)
	
	if ($('#more-views').length) {		
	
		setInterval(function() {
			if (!views_animating && !views_hover) {
				$('#more-views').mouseout();
			}
		}, 2000);
		
	};
	
	
	function fadeTooltip() {
		
		if (!tooltip_status) {
			
			if (!$.browser.msie) {
				$(tooltips).animate({opacity:0}, function() { 
					tooltip_status = false;
					$(tooltips).removeClass('not-shown');
				})
			} else {
				$(tooltips).hide(); 
				tooltip_status = false;
				$(tooltips).removeClass('not-shown');
				
			}
			
			
				
		};
		
	}
	
	function loadItemGallery(panel) {
		
		$('.image-data', panel).each(function () {
			
			var src = $(this).attr('rel');
			$(this).append('<img src="'+src+'" />')
			
		})
		
		$('a.image-data img', panel).attr('height', '70').attr('width', '99');
		$('span.image-data img', panel).attr('height', '228').attr('width', '336');
		
		$('a.image-data', panel).click(function() {
			
			var href = $(this).attr('href');
			var image = $(this).parent().find('img.image');
			
			image.attr('src', href);
			
			return false;
			
		})
			
		
		$('span.image-data img', panel).addClass('image');
		$('.image-data', panel).removeClass('image-data');
		
	}
	
	function loadItemDetail(panel) {
		
		$('.pane-carousel, .pane-toolbar, .pane-hotspots, #drawer-links').fadeOut(300, function() {
			$('#tour-drawer').animate('.state-item', function () {
				$(panel).fadeIn(300, function() {
					
				});				
			});
		});
		
		if ($.browser.msie) setTimeout(function() { $(panel).removeClass('not-shown')}, 299)
		
	}
	
	
	/* content paging */
	
	$('.content-pages').each(function() {
		
		var content_pages = $('.page', this);
		$(content_pages).hide();
		$(content_pages).eq(0).show();
		
		var total_pages = $(content_pages).length;
		
		if (total_pages > 1) {
			var buttons = '';
			
			for (var i=0; i < total_pages; i++) {
				buttons += '<a href="#">'+(i+1)+'</a> ';
			};
			
			$('.content-page-controls', this).append('<p></p>')
			$('.content-page-controls p', this).append(buttons);
			
			$('.content-page-controls a', this).eq(0).addClass('active');
			
		} 
				
		$('.content-page-controls a', this).click(function() {
						
			$(content_pages).hide();
			$(content_pages).eq($(this).index()).show();
			
			$(this).siblings().removeClass('active');
			$(this).addClass('active');
			
			return false;
			
		})
		
	})
	
	
	
	/* room tour detail tabs */

	$('.room-detail-tabs li a').click(function() {
		$(this).parents('.col-2').find('.contributions, .artifacts').toggleClass('not-shown');
		$(this).parents('ul').find('li').toggleClass('active');
		return false;
	})
	
	
	$('.artifacts ul li a').click(function() {
		
		$('.pane-item').hide();
		
		var panel = $('#' + $(this).attr('rel'));
		
		if ($.browser.msie) {
			loadItemDetail(panel);
		}
		
		panel.show();				
		
		loadItemGallery(panel);
		
		return false;
		
	})
	
	
	/* Calendar */
	
	//equalHeights($('#calendars .calendar .content'));
	equalHeights($('#donate-landing-options .pod'));
	
	
	/* Contact map */
	
	if ($('#contact-map').length) {
		
		if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById("contact-map"));
			map.setCenter(new GLatLng(55.4552, -4.3080), 13);
			map.setUIToDefault();
			map.addOverlay(new GMarker(new GLatLng(55.4552, -4.3080)));
		}
		
	};
	
	
	/* Vision tabs */
	
	$('#vision-masthead .arrow-tabs li a').hover(function(){
			
			$('#vision-details').show();
			$('#vision-details').removeClass('not-shown');
		
			// show page
			var index = $(this).parent().index();
			$('#vision-details .page').hide();
			$('#vision-details .page').eq(index).show();
		
			// indicate on menu
			$(this).parents('ul').find('li').removeClass('active');
			$(this).parent().addClass('active');
		
			return false;
		
		}) 
		
	$('#vision-masthead .arrow-tabs li a').click(function(){ return false; })
	
	
	/* Footer tab behaviour */
	
	$('.footer-tabs li').click(function() {
	
		$('.footer-tabs li')
		  .removeClass('active')
		  .eq($(this).index()) // pick out the clicked tab
		  .addClass('active');
		  
		$('.footer-panels .panel')
		  .removeClass('active')
		  .eq($(this).index()) // pick out the panel at the same level as the clicked tab
		  .addClass('active');
		  
		return false;
	})
	
	/* Search box clear */
	
	var searchBox = $('#search-box');
	
	if (searchBox.val()=='') {
		searchBox.val(searchBox.attr('title'));
	}
	
	searchBox
	  .focus(function() {
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	})
		.blur(function() {
		if ($(this).val()=='') {
			$(this).val($(this).attr('title'));
		}
	});
	
	
	/* Donate landing */
	
	if ($('#donate-amount').length) {
		
		var donate_defaut = $('#donate-amount').val();
		
		$('#donate-amount').click(function() {
			
			if ($(this).val() == donate_defaut) $(this).val('');
			$(this).addClass('selected');
		
		})
		
		$('#donate-landing-options a').click(function() {
			
			var amount = $(this).attr('rel');
			$('#donate-amount').val(amount);
			
			$('#donate-landing-arbitrary form').submit();
			
			return false;
		
		})
		
		
		
	};
	
	$("a[rel^='prettyPhoto']").prettyPhoto();
	
	/* YouTube for links */
	
	$('.blog-entry a[href*="youtube.com"]').each(function(){
	    // Replace the YouTube URL with the direct link to the SWF.
	  var newURL = $(this).attr('href').replace(/watch\?v=/,'v/');
	  $(this).attr('href', newURL);
	  // Add a class for styling
	  $(this).addClass('youtube');
	  // Remove the text from within the link
	  $(this).html('');
	    // Do the jQuery Media magic
	  $(this).media({width:425, height:344, type:'swf'});	  
	});
	
	$('.blog-entry a[href*="youtube.com"]').each(function(){
			    // Replace the YouTube URL with the direct link to the SWF.
		var newURL = $(this).attr('href').replace(/watch\?v=/,'v/');
		$(this).attr('href', newURL);
		// Add a class for styling
		$(this).addClass('youtube');
		// Remove the text from within the link
		$(this).html('');
		// Do the jQuery Media magic
		$(this).flash(
			{ height: 344, width: 425 },
			{ version: 8 },
			function(htmlOptions) {
				$this = $(this);
				htmlOptions.src = $this.attr('href');
				$this.before($.fn.flash.transform(htmlOptions));						
			});
		});
			
	
	/* map directions*/
	
	if ($('#map-directions').length) {
		
		var iconDH = new GIcon();
		iconDH.image = "/assets/ui/marker-dh.png";
		iconDH.shadow = "/assets/ui/marker-dh-shadow.png";
		iconDH.iconSize = new GSize(37, 40);
		iconDH.shadowSize = new GSize(55, 40);
		iconDH.iconAnchor = new GPoint(0, 20);
		iconDH.infoWindowAnchor = new GPoint(40, 0);
		iconDH.infoShadowAnchor = new GPoint(40, 0);
		
		$('#map-directions').jmap('init', {
			'mapType':'map',
			'mapCenter':[55.4556,-4.307955],
			mapShowjMapsIcon: false,
			mapZoom: 11
		});
		
		$('#map-directions').jmap('AddMarker', {
			'pointIcon': iconDH,
			'pointLatLng': [55.4556,-4.307955],
			'pointHTML': '<p class="map-title">Dumfries House</p>'}); //<p class="map-desc">Dumfries House</p>
			

		
	}
	
	
	/* Nearby attractions map */
	
	if ($('#map-attractions').length) {
		
		var iconDH = new GIcon();
		iconDH.image = "/assets/ui/marker-dh.png";
		iconDH.shadow = "/assets/ui/marker-dh-shadow.png";
		iconDH.iconSize = new GSize(37, 40);
		iconDH.shadowSize = new GSize(55, 40);
		iconDH.iconAnchor = new GPoint(0, 20);
		iconDH.infoWindowAnchor = new GPoint(40, 0);
		iconDH.infoShadowAnchor = new GPoint(40, 0);
		
		var iconAttr = new GIcon();
		iconAttr.image = "/assets/ui/marker-info.png";
		iconAttr.shadow = "/assets/ui/marker-info-shadow.png";
		iconAttr.iconSize = new GSize(23, 28);
		iconAttr.shadowSize = new GSize(37, 28);
		iconAttr.iconAnchor = new GPoint(0, 14);
		iconAttr.infoWindowAnchor = new GPoint(22, 0);
		iconAttr.infoShadowAnchor = new GPoint(22, 0);
		
		$('#map-attractions').jmap('init', {
			'mapType':'map',
			'mapCenter':[55.4556,-4.307955],
			mapShowjMapsIcon: false,
			mapZoom: 11
		});
		
		$('#map-attractions').jmap('AddMarker', {
			'pointIcon': iconDH,
			'pointLatLng': [55.4556,-4.307955],
			'pointHTML': '<p class="map-title">'+$('.map-data .dh .map-title').text()+'</p><p class="map-desc">'+$('.map-data .dh .map-desc').html()+'</p>'});
			
			
		$('.map-data div.entry').each(function() {
			
			var latlng = $(this).attr('rel');
			var latlngPairs = new Array;
			
			latlngPairs = latlng.split(',');
			
			var title = $('p.map-title', this).text();
			var desc = $('p.map-desc', this).html();
			var website = $('p.map-website', this).html();
			
			$('#map-attractions').jmap('AddMarker', {
				'pointIcon': iconAttr,
				'pointLatLng': [latlngPairs[0],latlngPairs[1]],
				'pointHTML': '<p class="map-title">'+title+'</p><p class="map-desc">'+desc+'</p><p class="map-website">'+website+'</p>'});
			
		})
		
	}
	
	/* tabbed content */
	
	if ($('.tabbed-content').length) {
	
		// set default states
		$('.tabbed-content .pane').hide();
		$('.tabbed-content .pane:first').show();
		$('.content-tabs li:first').addClass('active');
		
		//
		$('.content-tabs li a').click(function() {
			
			var index = $(this).parent().index();
			
			$('.tabbed-content .pane').hide();
			$('.tabbed-content .pane').eq(index).show();
			
			$('.content-tabs li').removeClass('active');
			$(this).parent().addClass('active');
			
			return false;
			
		})
		
	}
		
	if ($('#ticket-page-calendar').length) {
	
		/* ticket page JS */
	
		// set defaults 
	
		$('#ticket-slots-input').hide();
		$('#ticket-type-input').hide();
		$('#membership-input').hide();
		$('#refreshments-input').hide();
		$('#basket-holder').hide();
	
		$('#ticket-page-calendar').fullCalendar({
			// calendar is clickable
			//selectable: true,
			dayClick: function( date, allDay, jsEvent, view ) { 
				$('#ticket-page-calendar').fullCalendar( 'select', date, date, true );
				$('#ticket-slots-input').show();
			},
			eventClick: function(calEvent, jsEvent, view) {
				$('#ticket-page-calendar').fullCalendar( 'select', calEvent.start, null, true );
				$('#ticket-slots-input').show();
			},
			// default event data
			events: [
			        {
						type: 'event',
			            title: 'A nice event',
			            start: '2011-03-01',
			            description: 'This is a cool event',
						availablity: 'available'
			        },
					{
						type: 'event',
			            title: 'Another nice event',
			            start: '2011-03-10',
			            description: 'This is a cool event',
						availablity: 'booked'
			        },
					{
						type: 'event',
			            title: 'Another nice event',
			            start: '2011-03-20',
			            description: 'This is a cool event',
						availablity: 'available'
			        }
			    ],
				// show default events
				eventRender: function(event, element) {
				       element.addClass(event.type);
				       element.addClass(event.availablity);
				    }
		});
	
		$('#ticket-slots-input a').click(function() {
		
			// TODO set the slot value
		
			$('#ticket-type-input').show();
		
			return false;
		
		});
	
		$('#ticket-type-input .button a').click(function() {
		
			$('#membership-input').show();
			$('#refreshments-input').show();
			$('#basket-holder').show();
		
			return false;
		
		});
		
	};
		
	function ticketAvaiability(event, date, tickets) {
		alert('We are sorry, but there are only ' + tickets + ' ticket(s) remaining for this slot on "' + event + ': ' + date + '". Try selecting a different slot or different day, if available.');
	}
	
	// example call: ticketAvaiability("Tour name", "20th March 2011", "20");
	
	
	/* Ticket payment  */
	
	if($('#payment-type').length) {
		$('#payment-type').change(function() {
			if ($(this).val() == 'cheque') {
				$('.credit-card-related').hide();
				$('.cheque-info').show();
			} else {
				$('.credit-card-related').show();
				$('.cheque-info').hide();
			}
			
		})
	}

		
	
	/* Events index  */
	
	equalHeights($('#events-index-content .entry-content'));
		
	if ($('#events-index-content .entry').length > 4) {
	
		$('#events-index-content .entry:gt(3)').hide();
		
		$('#events-index-content .load-more a').click(function() {
		
			var visibleEvents = $('#events-index-content .entry:visible').length + 4;
			$('#events-index-content .entry:lt('+ visibleEvents +')').show();
						
			if (visibleEvents >= $('#events-index-content .entry').length) {
				
				$(this).parent().hide();
			}
					
			return false;
			
		});
	}
	else {
	
		$('#events-index-content .load-more').hide();
	}
	
	
	
	/* Events index calendar */

	
	if ($('#events-index-calendar').length) {
		
		$.getJSON("http://securetickets.dumfries-house.org.uk/data/events_feed_json/jsoncallback=?",function(data){		
		
		$('#events-index-calendar').fullCalendar({
			// calendar is clickable
			selectable: true,
			// when selecting a range
			select: function(startDate, endDate, allDay, jsEvent, view) {
				
				function addZero(num) {
					(String(num).length < 2) ? num = String("0" + num) :  num = String(num);
					return num;		
				}

				// select a date range and get the feed
				
				var from = startDate.getFullYear() + "" + addZero(startDate.getMonth()+1) + "" + addZero(startDate.getDate());
				var to = endDate.getFullYear() + "" + addZero(endDate.getMonth()+1) + "" + addZero(endDate.getDate());
				
				var url = "http://securetickets.dumfries-house.org.uk/data/events_feed_recent_json/"+from+"/"+to+"/jsoncallback=?"
			
						
				$.getJSON(url,function(data){	
				
					// empty the index
					$('#events-index-content, .events-summary-list ul').html('');

					// get the JSON
					var events = data.events;

					// loop through the events
					for (var key in events) {
					  $('#events-index-content').append(showIndexEvent(events[key]));
					  $('.events-summary-list ul').append(showSummaryEvent(events[key]));
					}
					
					var startDisplay = $.fullCalendar.formatDate(startDate, 'd MMMM');
					var endDisplay = $.fullCalendar.formatDate(endDate, 'd MMMM');
					
					if (startDate.getTime() == endDate.getTime()) {
						$('#upcoming').text('Events on ' + startDisplay);
						var noEventsString = "on this date";
					}
					else {
						$('#upcoming').text('Events between ' + startDisplay + ' and ' + endDisplay);
						var noEventsString = "during these dates";
					}
										
					if (data.events.length == 0) {
						$('#events-index-content').html('<p id="no-results"> <span class="title">There are no events '+noEventsString+'.</span> <span class="sub">Please select another date range using the calendar.</span></p>');
					};
				
				})	
				

			},
			eventClick: function(calEvent, jsEvent, view) {
				$('#events-index-calendar').fullCalendar( 'select', calEvent.start, null, true );
			},
			
			events: data.events,

			// show default events
			eventRender: function(event, element) {
			       element.addClass(event.type);
			       element.addClass(event.availablity);
			    }
	    })
		
		
		
	});
			
			
	}
		
	
	function showIndexEvent(data) {
		
		var html = '<div class="event entry">';
		html += '<img alt="" src="'+data.image+'">';
		html += '<div class="event entry-content">';
		html += '<h4 class="type">'+data.title+'</h4>';
		html += '<p class="date"><span class="em">'+data.day.value+'</span>'+data.day.attr.suffix+' '+data.month+'</p>';
		html += '<p class="time"><span class="em">'+data.start+'</span> until <span class="em">'+data.end+'</span></p>';
		html += '<p>'+data.description+'</p>';
		html += (data.ticketed == false) ? '' : '<p class="button red"><a href="'+data.url+'">Book tickets</a></p>';
		html += '<p class="link"><a href="'+data.url+'">More information</a></p>';
		html += '</div>';
		html += '</div>';
		
		return html;
		
	}
	
	function showSummaryEvent(data) {
		
		var html = '<li>';
		html += '<a href="#"><img src="'+data.image+'" alt="" width="50" height="35" /></a>';
		html += '<p class="title">'+data.title+' - '+data.day.value+data.day.attr.suffix+' '+data.month+'</p>';
		html += '<p class="meta">Starts '+data.start+' <a href="#">More info</a></p>';
		html += '</li>';
		
		return html;
		
	}
	
	
	
	
});

function equalHeights(element) {
	
	var tallest = 0;
	var property = ($.browser.msie && $.browser.version.substr(0,3)<="7.0") ? 'height' : 'min-height';
	
	$(element).each(function() {
		var height = $(this).height();
		if(height > tallest) tallest = height;
	});

	$(element).css(property, tallest);
	
}

