/**
* Standardlife.com 2010
*
* @author Brian Coit <brian@line.uk.com>
*/
(function($)
{
	/*
	* Default text for search field
	*/
	$(document).ready(function()
	{
		$('#searchinput').each(function()
		{
			var fld = $(this);

			var legendTxt = fld.parent()
				.find('legend')
				.text();

			if(fld.val() == '')
			{
				fld.val(legendTxt);
			}

			fld.focus(function()
			{
				if($(this).val() == legendTxt)
				{
					$(this).val('');
				}
			})
			.blur(function()
			{
				if($(this).val() == '')
				{
					$(this).val(legendTxt);
				}
			});
		});
	});

	$(document).ready(function()
	{
		$('table')
			.each(function()
			{
				var tbl = $(this);

				$(this).wrap('<div class="tbl-wrapper" />');

				$(this).parent().css({
					marginTop: tbl.css('margin-top'),
					marginBottom: tbl.css('margin-bottom'),
					marginLeft: tbl.css('margin-left'),
					marginRight: tbl.css('margin-right')
				});

				tbl.css({
					border: 0,
					margin: 0
				});

				$(this)
					.find('tr:last')
					.addClass('last-item');
			});
	})

	$(document).ready(function()
	{
		/**
		 * IE fixes (which needs runtime calcs)
		 */
		if($.browser.msie && parseInt($.browser.version) <= 7)
		{
			/**
			 * Fix for <= IE7's margin issues
			 */
			$('hr').each(function()
			{
				var hr = $(this);
				var prevObj = hr.prev();
				var hrMargin = parseInt(hr.css('margin-top'));
				var margin = parseInt(prevObj.css('margin-bottom'));
				var marginDiff = hrMargin - margin;

				var div = $('<div />').css({
					backgroundImage: hr.css('background-image'),
					backgroundRepeat: 'repeat-x',
					clear: 'both',
					backgroundPosition: '0 0',
					height: hr.css('height'),
					fontSize: '1px',
					lineHeight: '1px'
				});

				div.css({
					marginTop: hr.css('margin-top'),
					marginBottom: hr.css('margin-bottom')
				});

				hr.css({ display: 'none' }).wrap(div);
				div.css('margin-top', marginDiff + 'px');
			});
		}

		if($.browser.msie && parseInt($.browser.version) < 7) //ie6
		{
			/* prevents buttons without specified widths breaking in ie6  */
			$('span.button a').each(function()
			{
				$(this).html($(this).text().replace(/ /g, '&nbsp;'));
			});
		}
	});

	/**
	* Expand/contract footer text
	*/
	$(document).ready(function()
	{
		var ctrl = $('#footer-legal-text p.ctrl');
		var text = ctrl.html();
		var container = ctrl.parent();
		var containerInner = container.find('div');

		ctrl.html('');
		containerInner.hide();

		containerInner.css({ width: '100%' });

		var ctrlLink = $('<a name="footer-text" href="#">' + text + '</a>')
			.appendTo('#footer-legal-text p.ctrl')
			.click(function(e)
			{
				e.preventDefault();

				if(containerInner.not(':animated'))
				{
					if(containerInner.is(':visible'))
					{
						ctrlLink.removeClass('open');

						containerInner
							.slideUp(300);
					}
					else
					{
						ctrlLink.addClass('open');

						containerInner
							.slideDown(300);

						// added by christopher (make newly displayed footer text the focus through <a> anchor tag)
						goToByScroll("footer-legal-text");
					}
				}
			});

				// For the below script to work all images wanting to have this applied
				// should have widths and hieghts set as well as the class "rounded"
				// - christopher de beer
				if (!($.browser.msie && parseFloat($.browser.version) < 7)) {
						$('img').bind('load', function()
						{
								pic_real_width = this.width;
								pic_real_height = this.height;

								if ($(this).hasClass('rounded')) {
										$(this).wrap(function() {
												return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ pic_real_height + 'px; width: '+ pic_real_width + 'px;" class="rounded" />';
										});
								} else if ($(this).hasClass('toprounded')) {
										$(this).wrap(function() {
												return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ pic_real_height + 'px; width: '+ pic_real_width + 'px;" class="toprounded" />';
										});
								} else if ($(this).hasClass('smallrounded')) {
										$(this).wrap(function() {
												return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ pic_real_height + 'px; width: '+ pic_real_width + 'px;" class="smallrounded" />';
										});
								}
						})
						.each(function()
						{
							if(this.complete)
								$(this).trigger('load');
						});
				}

				// accordian style/functionality for QA and FAQ

				$('ul.qa .answer').hide();
				$('ul.qa li').addClass("closed").find(".question").click( function () {
						$(this).parent().toggleClass("closed").toggleClass("open");
						$(this).parent().find(".answer").slideToggle();
						});


				// primary content puffs need to be made the same height

				$("#primary-content .puffs .row").each(function() {
				equalHeight($(this).find(".puff-inner"));
				});

				// create classes for table columns

				$("#primary-content table td:last-child").addClass("last-item");
				$("#primary-content table th:last-child").addClass("last-item");

				$("#primary-content table td:first-child").addClass("first-item");
				$("#primary-content table th:first-child").addClass("first-item");

				$("#primary-content table tr:last-child").addClass("bottom");
				$("#primary-content table tr:first-child").addClass("top");

				// validate any forms on the page

				$("form input[type='submit']").click(function() {
						$(this).closest("form").validate({
								invalidHandler: function(form, validator) {
										$(".error-puff").show();
								 },
								errorPlacement: function(error, element) {
										error.insertAfter( element );
										var errortolist = error.attr("htmlfor");
										// alert(errortolist);
										var labelforerror = $("label[for="+errortolist+"]").text();
										$(".error-puff .error-list").append("<li htmlfor='"+errortolist+"'>"+labelforerror +" is required</li>");
								},

								errorElement: "span",
								errorClass: "error",
								submitHandler: function(form) {
								form.submit();
								}}
								);
						$(this).addClass("validating");
						$(".error-puff .error-list li").each (function() {
								var thiserror = $(this).attr("htmlfor");
								if ($("#" + thiserror).hasClass("error")) {} else {
										$(this).remove();
								}
						});
				});


// Calender tabbing from .calender > .sections

/*	amended on 14/01/2011  probelm with timeline page */
/* if ($(".calender").length)   */

if ($(".calender").length && $('.calender').find('.pagination').length)

				{
					var container = $(".calender");
					var pager = $(".calender .pagination")//.remove();

					container
						.addClass("js")
						.each(function()
						{
							_container = $(this);

							// create pagination link container
							var tabs = $(".section", _container);

							/*var tc = $('<ul />')
									.addClass('pagination')
									.prependTo(_container);*/

							var tc = pager;

							tc.find('li').each(function()
							{
								var __li = $(this);

								if(__li.find('a[rel^=year]').length)
								{
									__li.remove();
								}
							});

							var otherEls = tc.find('li');

							// loop through sections and add their titles as links in the link container

							tabs.each(function()
							{
								var tab = $(this);

								if(tab.attr('title'))
								{
									var title = tab.attr('title');
								}
								else
								{
									var title = $.trim($("h2",tab).text());
								}

								$(".pagination").prepend("<li><a class='paglink' href='#'>" + title + "</a></li>");
							});
							//$('.pagination a:not(.paglink)',_container).remove();
							otherEls.each(function() { $(this).prependTo('.pagination'); });


							var links = $(".pagination li a.paglink", _container);

							// add fclick function to each of the links based on the title and relative anchor

							links.click(function(e){
									e.preventDefault();
									_link = $(this);
									$(".pagination li").removeClass("current");
									$(".section",_container).removeClass("current").hide();
									var linkto = $.trim(_link.text());

									if($('.section[title='+linkto+']').length)
									{
										$('.section[title='+linkto+']')
											.addClass('current')
											.show();
									}
									else
									{
										$(".section a[name=" + linkto +  "]")
												.closest(".section")
												.addClass("current")
												.show();
									}
									_link.closest("li").addClass("current");

									// check for disabled links and vice vera

									if($(".pagination li a[rel=print]",_container).length)
									{
										if (_link.parent().prev().prev().hasClass("next")) {
												$(".pagination li.next",_container).addClass("disabled");
										} else {
												$(".pagination li.next",_container).removeClass("disabled");
										}
									}
									else
									{
										if (_link.parent().prev().hasClass("next")) {
												$(".pagination li.next",_container).addClass("disabled");
										} else {
												$(".pagination li.next",_container).removeClass("disabled");
										}
									}

									if (_link.parent().next().hasClass("prev")) {
											$(".pagination li.prev",_container).addClass("disabled");
									} else {
											$(".pagination li.prev",_container).removeClass("disabled");
									}

							});

							// hide all but the first tab/sections and make that link active

							$(".section",_container).hide();
							//$(".pagination li:last", _container).addClass("current");
							var currentElement;
							$('.pagination li', _container).each(function()
							{
								var _link = $(this).find('a[class=paglink]');
								
								if(_link.length)
								{
										currentElement = $(this);
								}
							});
							currentElement.addClass('current');
							$(".section:first", _container).addClass("current").show();

							// create previous and next buttons

							var prevbutton = "<li class='prev disabled'><a href='#'>Previous</a></li>";
							var nextbutton = "<li class='next'><a href='#'>Next</a></li>";
							$(".pagination", _container).append(prevbutton);
							$(".pagination", _container).prepend(nextbutton);

							// add prev next button click functionality

							$("li.next a", _container).click(function(e){

									e.preventDefault();
									if ($(this).parent().hasClass("disabled")) {}
									else {

											if($(".pagination li.current", _container).prev().find('a.paglink').length)
											{
												$(".pagination li.current", _container)
														.removeClass("current")
														.prev().addClass("current");
												$(".section.current", _container)
														.removeClass("current")
														.hide()
														.next().show().addClass("current");

												$(".pagination li.prev").removeClass("disabled");
											}



												// if the next one is button then make disabeld
												if($('.pagination').find('.print').length || $('.pagination').find('a[rel=print]').length)
												{
													if ($(".pagination li.current",_container).prev().prev().hasClass("next"))
													{
														$(this).parent().addClass("disabled");
													}
												}
												else
												{
													if ($(".pagination li.current",_container).prev().hasClass("next"))
													{
														$(this).parent().addClass("disabled");
													}
												}
									}
							});

							$("li.prev a", _container).click(function(e){

									e.preventDefault();
									if ($(this).parent().hasClass("disabled")) {}
									else {


											$(".pagination li.current", _container)
													.removeClass("current")
													.next().addClass("current");
											$(".section.current", _container)
													.removeClass("current")
													.hide()
													.prev().show().addClass("current");

											$(".pagination li.next").removeClass("disabled");

											// if the next one is button then make disabeld

											if ($(".pagination li.current",_container).next().hasClass("prev")){
													$(this).parent().addClass("disabled");
											}
									}
							});
								
							// get current user year
							var curYear = (new Date()).getFullYear();
							
							// default to current year if available, otherwise will leave at latest year
							$('.pagination li', _container).each(function()
							{
								var _link = $(this).find('a[class=paglink]');

								if(_link.text() == curYear)
								{
									_link.click();
								}
							});
						});
				}


				function equalHeight(group) {
						var tallest = 0;
						group.each(function() {
								var thisHeight = $(this).height();
								if(thisHeight > tallest) {
										tallest = thisHeight;
								}
						});
						group.height(tallest);
				}

				function goToByScroll(id){
						$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
				}

	});
})
(jQuery);

/**
 * Expanding tables
 *
 * Takes a table
 *
 * @author Brian Coit <brian@line.uk.com>
 */
(function($)
{
	$(document).ready(function()
	{
		$('table.expanding').each(function()
		{
			var tbl = $(this);
			var tblWrapper = tbl.parent();
			var j = 0;

			tblWrapper.addClass('tbl-expanding');

			var div = $('<div />')
				.addClass('tbl-section-wrapper');

			var newTbl = $('<table />')
				.addClass('expanding')
				.addClass('processed')
				.appendTo(div);

			/* set th/td widths - forces widths */
			$(function()
			{
				tbl.find('td, th').each(function()
				{
					$(this).width($(this).width());
				});
			});

			tbl.find('tr').each(function(i)
			{
				var _tr = $(this);

				/* create a new wrapper for each section */
				if(_tr.find('> .section').length)
				{
					var t = $('<div />')
						.addClass('tbl-section-heading')
						.appendTo(tbl.parent());

					var tHeading = $('<table />')
						.addClass('expanding')
						.addClass('processed')
						.appendTo(t);

					var tCell = tHeading.find('td');

					tHeading.append(_tr);




					t.find('td').removeClass('opened').addClass('closed');

					div = $('<div />')
						.addClass('tbl-section-wrapper')
						.hide()
						.appendTo(tbl.parent());

					var _thisDiv = div;

					newTbl = $('<table />')
						.addClass('expanding')
						.addClass('processed')
						.appendTo(div);

					t.find('a').click(function(e)
					{
						e.preventDefault();

						if(_thisDiv.is(':animated'))
						{
							return;
						}

						if(_thisDiv.is(':visible'))
						{
							$(this).parent().removeClass('opened');
							$(this).parent().addClass('closed');
							_thisDiv.slideUp(300);
						}
						else
						{
							$(this).parent().addClass('opened');
							$(this).parent().removeClass('closed');
							_thisDiv.slideDown(300);
						}
					});
				}
				else
				{
					newTbl.append(_tr);
				}
			});
			tbl.remove();

			/* expand the first table element since we're collapsing them all by default */
			$(tblWrapper.find('.tbl-section-heading').get(0)).find('a').click();
		});
	});
})
(jQuery);

/**
 * Infographic / hotmap
 */
(function()
{
	$(document).ready(function()
	{
		$('.hotmap').each(function()
		{
			var ul = $('> ul', this);
			var li = $('> li', ul).removeClass('active');

			li.each(function()
			{
				var _li = $(this);

				var _content = $('> ul', this)
					.hide();

				_li.click(function(e)
				{
					e.preventDefault();
					
					_content.find('a').click(function()
					{
						var _href = $(this).attr('href');
						
						if(_href)
						{
							window.location.href = _href;
						}
					});
					
					li.find('ul').hide();

					_li.addClass('active')
						.siblings()
						.removeClass('active');

					_content
						.show()
						.siblings()
						.find('> ul')
						.hide();
						
					resetPosition(_content);
				});

				function resetPosition(element)
				{
					var containerHeight = ul.outerHeight();
					var liTop = Math.round(parseFloat(_li.position().top));
					var containerTop = Math.round(parseFloat(ul.position().top));
					var baselinePosition = element.innerHeight() + element.position().top;
					
					if(baselinePosition >= containerHeight)
					{
						var diff = baselinePosition - containerHeight;
						
						element.css({
							top: (parseInt(element.css('top')) - diff) + 'px'
						});
					}
					else
					{
						element.css({
							top: liTop + 'px'
						})
					}
				}
			});
			
			$(li.get(0)).find('> a').click();
		});
	});
})
(jQuery);
