/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * equalizes the heights of all elements in a jQuery collection
	 * thanks to John Resig for optimizing this!
	 * usage: $("#col1, #col2, #col3").equalizeCols();
	 */
	 
	$.fn.equalizeCols = function(){
		var height = 0,
			reset = $.browser.msie ? "1%" : "auto";
  
		return this
			.css("height", reset)
			.each(function() {
				height = Math.max(height, this.offsetHeight);
			})
			.css("height", height)
			.each(function() {
				var h = this.offsetHeight;
				if (h > height) {
					$(this).css("height", height - (h - height));
				};
			});
			
	};
	
})(jQuery);

$(document).ready(function() {
	
	var body = $("body").addClass('js');
	
	if ($.browser.msie && $.browser.version < 8 && $('body').width() < 1200) {
		$('div#header form').css('right', '120px');
	}
	
	/*
		Add inner-shadow to base of each tab
	*/
	$("ul.primary > li").each(function() {
		var li = $(this);
		li.append("<span class='shadow'></span>");
		if (li.hasClass("selected")) {
			$(this).find("span.shadow").hide();
		} else {
			li.hover(function(e) {
				$(this).find("span.shadow").hide();
			}, function(e) {
				$(this).find("span.shadow").show();
			});
		};	
	});
	
	/*
		If secondary nav spills onto two lines reduce margins so that they fit on one
	*/
	var secondary_li_width_with_margin = 0;
	var secondary_li_width_no_margin = 0;
	var secondary_li_count = 0;
	var secondary_ul_width = 864;
	$('ul.primary li.selected ul.secondary li').each(function(i) {
		secondary_li_width_with_margin += $(this).width() + parseInt($(this).css('margin-right'));
		secondary_li_width_no_margin += $(this).width() - parseInt($('a', this).css('margin-left'));
		secondary_li_count = i;
	});
	if (secondary_li_width_with_margin >= secondary_ul_width) {
		var secondary_margin = Math.floor((secondary_ul_width - secondary_li_width_no_margin) / secondary_li_count);		
		$('ul.secondary li:first a').css('margin-left', 'auto');
		$('ul.secondary li a').css('margin-left', 0);
		$('ul.secondary li').css('margin-right', secondary_margin);
	}
	
	/*
		Flashify headings in promos
	*/
	$("#home-hero, .promo").each(function(i) {
		var promo = $(this);
		
		$("h2, h3", promo).each(function(j) {
			$(this).attr("id", "h-" + i + "-" + j);

			var colour = "blue";
			var width = 238;
			
			if (promo.hasClass("orange")) { colour = "orange"; }
			if (promo.hasClass("green")) { colour = "green"; }
			if (promo.hasClass("beige")) { colour = "beige"; }
			if (promo.hasClass("dark-green")) { colour = "darkgreen"; }
			
			if ($(this).hasClass('wide')) { colour += '-wide'; width = 500; }
			
			var text = $(this).text();
			
			var so = new SWFObject("/assets/swf/h3-" + colour + ".swf", "h-" + i + "-" + j, width, "28", "8", "#ffffff");
			so.addVariable("text", escape(text));
			so.addParam("menu", "false");
			so.addParam("quality", "high");
			so.addParam("wmode", "transparent");
			so.write("h-" + i + "-" + j);
			
			$(this).append('<span class="alt-text">' + text + '</span>');
		});
		
	});
	
	/*
		Flashify headings in the footer
	*/
	$("#footer h2").each(function(i) {
		$(this).attr("id", "footer-" + i);
		
		var swf = "h3-darkgreen.swf";
		if ($(this).parent().attr("id") == "footer-flickr") {
			swf = "h3-visitr.swf";
		}
		
		var text = $(this).text();
		
		var so = new SWFObject("/assets/swf/" + swf, "footer" + i, "238", "28", "8", "#ffffff");
		so.addVariable("text", escape(text));
		so.addParam("menu", "false");
		so.addParam("quality", "high");
		so.addParam("wmode", "transparent");
		so.write("footer-" + i);
		
		$(this).append('<span class="alt-text">' + text + '</span>');
		
	});
	
	/*
		Google Mapify the Map and Directions page
	*/	
	if ($("body").hasClass("map-and-directions")) {
		if (!GBrowserIsCompatible()) return;
		var map = new GMap2(document.getElementById("map"));		
		map.setCenter(new GLatLng(51.6130667483, -0.64537167549), 12);
		map.setMapType(G_NORMAL_MAP);
		map.addControl(new GSmallMapControl());
		map.addControl(new GOverviewMapControl());
		map.addOverlay(new GTrafficOverlay());

		icon = new GIcon();
		icon.image = "http://www.google.com/mapfiles/marker.png";
		icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		icon.iconSize = new GSize(20, 34);
		icon.shadowSize = new GSize(37, 34);
		icon.iconAnchor = new GPoint(9, 34);
		icon.infoWindowAnchor = new GPoint(9, 2);
		icon.infoShadowAnchor = new GPoint(18, 25);
		
		map.addOverlay(new GMarker(new GPoint(-0.64537, 51.613066), { title: "Bekonscot Model Village", icon: icon}));
		
		$(document).unload(function() {
			GUnload();
		});	
	}
	
	/*
		Add context to tertiary-level menu lists
	*/	
	$('div.subsection-seealso li.selected a span').each(function() {
		var text = $(this).html();
		$(this).html(text + ' (you are here)')
	});
	
	/*
		Light Railway timetable context titles
	*/
	if (body.attr('id') == 'models-and-attractions' && body.hasClass('light-railway')) {
		$("td.running").attr('title', 'Trains are running on this day');
		$("td.running-today").attr('title', 'Trains are running today');
		$("td.not-running").attr('title', 'Trains are not running on this day');
		$("td.not-running.today").attr('title', 'Trains are not running today');
		$("td").hover(function() { $(this).addClass('hover') }, function() { $(this).removeClass('hover') });
	}
	
	if (body.attr('id') == 'models-and-attractions' && body.hasClass('history')) {
		$('#content a.chunky-small').click(function(e) {
			e.preventDefault();
			var group_name = 'group' + $(this).attr('href').match(/[0-9]/)[0];
			$('div.hidden a[rel='+group_name+']:first').click();
		});
	}
	
	$('body#models-and-attractions ul#attractions li, body#fun-and-games ul#games li')
	.hover(function() {
		$(this).addClass('hover');
		$(this).css('cursor', 'pointer');
	}, function() {
		$(this).removeClass('hover');
	})
	.click(function(e) {
		e.preventDefault();
		var href = $(this).find('a').attr('href');
		if (href.indexOf('http://') == -1) {
			window.location.href = href;
		} else {
			window.open(href);
		}
	});
	
	var home_image_gallery = $("#home-hero div.image-gallery div.gallery");
	var home_image_gallery_html = home_image_gallery.html();
	function applyHomeImageCarousel(apply) {
		home_image_gallery.html(home_image_gallery_html);
		if (!apply) return;
		home_image_gallery.jCarouselLite({
			auto: 3000,
			speed: 650,
			circular: true,
			visible: 1,
			scroll: 1,
			easing: 'easeout'
		});
	}
	
	if (body.attr('id') == 'home') {
		applyHomeImageCarousel(true);
		$('#home-hero ul.tabs a').click(function(e) {
			e.preventDefault();
			$('#home-hero').find('.visible').removeClass('visible');
			$('#home-hero ul.tabs a').removeClass('selected');
			var type = $(this).attr('href').match(/=(.*)$/)[1];
			$('#home-hero').find('.' + type).addClass('visible');
			$(this).addClass('selected');
			
			if (type == 'image-gallery') {
				applyHomeImageCarousel(true);
			} else {
				applyHomeImageCarousel(false);
			}
			
		});
		$('#home-hero div.video-player div.description li a').click(function(e) {
			var id = $(this).attr('href').match(/=([0-9]+)$/)[1];
			var embed = $('#home-hero div.video-player div.video').html();
			var html = embed.replace(/clip_id=[0-9]+/gi, 'clip_id=' + id);
			$('#home-hero div.video-player div.video').html(html);
			e.preventDefault();
		});
	}
	
	$('a.nolink').click(function(e) {
		e.preventDefault();
	});
	
	$('body:not(#search) div#content a[href^="http"], #footer-flickr li a').each(function() {
		$(this).attr('title', 'Opens external link in a new window');
		$(this).click(function(e) {
			e.preventDefault();
			window.open($(this).attr('href'));
		});
	});
	
	if (body.hasClass('webcam')) {
		
		var webcam = $('#webcam');
		var caption = webcam.find('span');
		var image = webcam.find('img');
		
		var time = null;
		var timeout = null;
		
		image.load(function() {
			timeout = null;
			clearTimeout(timeout);
			timeout = setTimeout(function() {
				setImage();
			}, 5 * 1000); //seconds
		});
		
		function setImage() {
			image.attr('src', 'http://www.bekonscot.co.uk/assets/php/webcam.php?' + (new Date).getTime());
		}
		
		setImage();
				
	}
	
	$('#promo-corner').click(function() {
		var img = $('img', this).attr('src').split('/');
		pageTracker._trackEvent('Promo', 'Click', 'top-corner (' + img[img.length - 1] + ')');
	});
	
	$('div.promo div.bottom a').click(function() {
		var id = $(this).parents('.promo').attr('class').split(' ');
		pageTracker._trackEvent('Promo', 'Click', id[2]);
	});
	
	$("a[href$='.pdf']").click(function() {
		var file = $(this).attr('href').split('/');
		pageTracker._trackEvent('Downloads', 'PDF', file[file.length - 1]);
	});
	
	$('#breadcrumb a').click(function() {
		pageTracker._trackEvent('Breadcrumb', 'Click', $(this).text());
	});
	
	$('#home-hero ul.tabs a').click(function() {
		pageTracker._trackEvent('Home Hero', 'Tab', $(this).attr('href').replace(/\?view=/,''));
	});
		
});