﻿/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/* Function to get query string */
function getParameterByName( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
	{
		return "";
	}
	else
	{
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}
function getParameterByNameFromString( name, str )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( str );
	if( results == null )
	{
		return "";
	}
	else
	{
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}

//Cookie functions
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}


/* Footer plugin */
(function ($) {
	$.fn.footerActivate = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);
			if(readCookie("footerOpen")=="true")
			{
				$this.addClass("footer-open");
				$this.find("#footer").show();
			}

			//Attach click functionality to the footer bar
			$this.find("#footer-bar").click(function () {
				var $footer = $this.find("#footer");
				$footer.clearQueue();

				if ($footer.is(":visible")) {
					_gaq.push(['_trackEvent', 'Footer', 'Clicked to close the footer']);
					//Fix to get around firefox flicker
					$("body").scrollTo($("#header-strip"), 1000, { easing: 'easeOutQuad', onAfter: function(){
							$footer.slideUp("normal");
						} 
					});
					createCookie("footerOpen","false");
					$("#footer-container").addClass("footer-closed").removeClass("footer-open");
				}
				else {
					_gaq.push(['_trackEvent', 'Footer', 'Clicked to open the footer']);
					$footer.slideDown("normal", function () {
						$("body").scrollTo($footer, 1000, { easing: 'easeInQuad' });
					});
					createCookie("footerOpen","true");
					$("#footer-container").addClass("footer-open").removeClass("footer-closed");
				}

				return false;
			});

			//Enable location toggle
			var $selectLocation = $this.find(".select-location");
			$selectLocation.find("a").click(function () {
				if ($(this).hasClass("selected")) {
					return false;
				}
				else {
					$selectLocation.find(".selected").removeClass("selected");
					$(this).addClass("selected");
					$("#selected-location").removeClass().addClass($(this).attr("href").replace("#", ""));
				}
				return false;
			});

		});
	};
})(jQuery);


/* Watermark plugin */
(function ($) {
	$.fn.watermark = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);
			var $wm = $this.find("label");
			var $input = $this.find("input[type='text']");
			if($input.val()!="")
			{
				$wm.hide();
			}

			$wm.click(function(){
				$input.focus();
				return false;
			});

			$input.focus(function(){
				$wm.hide();
			});

			$input.blur(function(){
				if($input.val()==""){
					$wm.show();
				}
			});
		});
	};
})(jQuery);



/* Lightbox video plugin */
(function ($) {
	$.fn.lightboxvideo = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);
			var videoId = $(this).attr("href").replace("http://player.vimeo.com/video/","").split("?")[0];

			$this.unbind("click");
			$this.click(function(){
				//Check whether a lightbox dialog has already been created
				var $lightbox = $('#vlb-'+videoId);
				if($lightbox.length==0)
				{
					$lightbox = $('<div id="vlb-'+videoId+'" />');
					$lightbox.append('<iframe width="900" height="503" frameborder="0" src="'+$this.attr("href")+'"></iframe>');

					$lightbox.appendTo("body");
					$lightbox.dialog({
						autoOpen: false,
						modal: true,
						width: 900,
						position: ['center', 'top']
					});
				}
				//Then open it
				$lightbox.dialog('open');
				return false;
			});
		});
	};
})(jQuery);


/* Events basket plugin */
(function ($) {
	$.fn.eventsbasket = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		function generateURL(str){
			str = str.replace("events.aspx","events.aspx/EventsBasketAJAX");
			var eventObj =
			{
				eventId : getParameterByNameFromString("eventId",str),
				action : getParameterByNameFromString("action",str),
				ajaxURL : str
			}
			return eventObj;
		}

		var $basketContainer = $(".events-basket");
		var $basket = $(".events-basket ul");

		$basket.find(".remove-event").live("click",function(){
			var eventId = $(this).parent().attr("id").split("-")[1];
			var $thisLink = $(this);
			var $thisLinkParent = $thisLink.parent();
			var eventObj = generateURL(this.href);

			$.get(eventObj.ajaxURL,function(response, status, xhr){
				if(status=="success")
				{
					//Re-display the add button
					$(".events-list li .button-list li a[href*='eventId="+eventObj.eventId+"'],#header-right .featured-content .button-list li a[href*='eventId="+eventObj.eventId+"']").parent().fadeIn();

					if($thisLinkParent.parent().find("li").length>1)
					{
						$thisLinkParent.remove();
					}
					else if($thisLinkParent.parent().find("p:contains(No events selected)").length==0){
						$basketContainer.find("h3").after("<p>No events selected</p>");
						$basketContainer.find("input").hide();
						$thisLinkParent.parent().remove();
					}
				}
					
			});
			return false;
		});

		return $(this).each(function () {
			var $this = $(this);
			var $events = $(".event-listing,.featured-content");
			
			$events.find(".add-link").click(function(){
				var $thisLink = $(this);
				var $thisLinkParent = $thisLink.parent();
				var eventObj = generateURL(this.href);

				$.get(eventObj.ajaxURL,function(response, status, xhr){
					if(status=="success")
					{
						var $response = $('"'+response+'"');
						var $event = $response.find("#event-"+eventObj.eventId);

						if($basketContainer.find("ul").length==0)
						{
							$basketContainer.find("p").remove();
							$basketContainer.find("h3").after("<ul/>");
							$basketContainer.find("input").fadeIn("normal",function(){$(this).css("display","inline-block");});
						}
						//Make sure we don't duplicate basket items
						if($(".events-basket ul #event-"+eventObj.eventId).length==0)
						{
							$(".events-basket ul").append($event);
						}
						$thisLinkParent.hide();
					}
				});
				return false;
			});

		});
	};
})(jQuery);


/* Form validation plugin */
(function ($) {
	$.fn.formValidation = function (options) {
		var settings = {
			success : null
		};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);
			var $inputs = $this.find("li input[type='text']");

			$inputs.focus(function () {
				var $thisLI = $(this).parent();
				if ($thisLI.hasClass("has-error")) {
					$thisLI.find(".error-popup").fadeIn();
				}
			});

			$inputs.blur(function (e) {
				var $thisLI = $(this).parent();
				if ($thisLI.hasClass("has-error")) {
					$thisLI.find(".error-popup").fadeOut();
				}
			});

			$inputs.live('blur',function(e){liveValidate(this);});

			//Live validate each input individually
			function liveValidate(thisInput)
			{
					var $thisLI = $(thisInput).parent();
					var $thisValidators = $thisLI.find(".validation-error");
					var thisValid = true;
					var errorMessage = "";
					$thisValidators.each(function () {
						if ($(this)[0].isvalid == false) {
							thisValid = false;
							errorMessage += $(this)[0].errormessage;
						}
					});
					$thisLI.find(".error-popup").remove();

					if (thisValid == false) {
						//format the input field
						$thisLI.addClass("has-error");
						$thisLI.append("<div class='error-popup'>" + errorMessage + "</div>");
					}
					else {
						//remove error formatting
						$thisLI.removeClass("has-error");
					}

				return false;
			}

			$this.find("input.action-link").click(function(e){
				$inputs.each(function(){
					liveValidate(this);
				});
				
				$this.find(".has-error").eq(0).find("input[type='text']").blur().focus();

				if ($this.find(".has-error").length == 0) {
					if(settings.success!=null)
					{
						//Assume if there are no errors flagged that it's safe to trigger the ajax request
						settings.success();
						return false;
					}
					else{
						return true;
					}
				}

				return false;
			});
		});
	};
})(jQuery);


/* Subscribe to newsletter plugin */
(function ($) {
	$.fn.subscribeNewsletter = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);
			var $li = $(this).parent().parent();
			var $inputs = $li.find("input[type='text']");

			$inputs.focus(function(){
				var $thisLI = $(this).parent().parent();
				if($thisLI.hasClass("has-error"))
				{
					$thisLI.find(".error-popup").fadeIn();
				}
			});

			$inputs.blur(function(){
				var $thisLI = $(this).parent().parent();
				if($thisLI.hasClass("has-error"))
				{
					$thisLI.find(".error-popup").fadeOut();
				}
			});

			$this.find("input.action-link").click(function(e){
				e.preventDefault();
				
				$inputs.each(function(){
					var $thisLI = $(this).parent().parent();
					var $thisValidators = $thisLI.find(".validation-error");
					var thisValid = true;
					var errorMessage = "";
					$thisValidators.each(function(){
						if($(this)[0].isvalid==false){
							thisValid = false;
							errorMessage += $(this)[0].errormessage;
						}
					});
					$thisLI.find(".error-popup").remove();

					if(thisValid == false){
						//format the input field
						$thisLI.addClass("has-error");
						$thisLI.append("<div class='error-popup'>"+errorMessage+"</div>");
					}
					else{
						//remove error formatting
						$thisLI.removeClass("has-error");
					}

				});

				$this.find(".has-error").eq(0).find("input[type='text']").blur().focus();

				if( $this.find(".has-error").length==0 ){
					//Assume if there are no errors flagged that it's safe to trigger the ajax request
					$.ajax({
						type: "POST",
						url:"/webservices/webservices.asmx/ProcessNewsletterSubscription",
						data:"{'firstname':'"+$this.find("input[id*='FirstName']").val()+"','lastname':'"+$this.find("input[id*='LastName']").val()+"','email':'"+$this.find("input[id*='Email']").val()+"','company':'"+$this.find("input[id*='Company']").val()+"'}",
						dataType:"json",
						contentType: "application/json; charset=utf-8",
						success: function(data){
							if(data.d.success == true){
								$this.find("fieldset").replaceWith("<p>Thank you for subscribing to our newsletter</p>").hide().fadeIn();
							}
						}
					});
				}
				return false;
			});
		});
	};
})(jQuery);


/* People profile plugin */
(function ($) {
	$.fn.interactiveprofile = function (options) {
		var settings = {
			pageNum : 1
		};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {

			//Define the container
			var $container = $(this);

			//Initialise the object if necessary
			if(typeof($container.data("initialised")) == "undefined"){
				$container.data("totalProfiles",0);
				$container.data("initialised",true);

				//Preload the popup background image
				var $popupBgImg = $('<img />').attr('src', '/assets/images/modules/people/people-dialog.png');

				//Retrieve page number from the querystring, else use the page number specified in settings.
				var pageNum = getParameterByName("page")!=""?parseInt(getParameterByName("page"),10):settings.pageNum;

				//Hide the pagination and output show more button
				if($(".show-more-button").length==0 && pageNum==1)
				{
					$container.find(".pagination").hide().after("<a href='?filterBy=&page="+parseInt(pageNum+1)+"' class='show-more-button'>Show more people</a>");
				}

				$(".section-1").data("sectionNum",1);
				preloadSection($(".section-1"));
				attachPopupFunctionality();
			}
		  
			//Remove any click events from the button
			$(".show-more-button").unbind("click");

			//Function to trigger ajax call
			function callAjax(pageNum,showOnComplete){
				//If the section already exists, then no need to make an ajax request
				if( $(".section-"+(pageNum+1)).length==0 )
				{
					$.ajax({
						url: 'us/PeopleListingAJAX.aspx?filterBy=&page='+parseInt(pageNum+1),
						success: function(data) {
							//Get total number of profiles from the data
							if($container.data("totalProfiles")==0)
							{
								$container.data("totalProfiles",parseInt($(data).find("#profile-count").text(),10));
							}

							//Select the profiles list from the data
							var $data = $(data).find("ul").addClass("section-"+(pageNum+1));

							//Make the elements hidden before adding them to the page
							$data.hide();

							//Find the last profile list on the page
							var $ul = $container.find("ul.profile-list:last");

							//Create the new section and insert it after the last profile list
							var $newSection = $data.insertAfter($ul);
							$newSection.data("sectionNum",pageNum+1);

							//Define the next page number
							var nextPage = pageNum + 1;
							$newSection.data("nextPage",nextPage);

							//Apply the plugin to the new section
							$("#profiles").interactiveprofile({pageNum:nextPage});

							if(showOnComplete)
							{
								showMore();
							}
						}
					});
				}
			}

			//Function to show next section
			function showMore(){
				var $newSection = $(".profile-list:hidden");

				if($newSection.length>0)
				{
					//Once the images for this section have loaded, preload the next
					preloadSection($newSection);

					//Show the new section
					$newSection.fadeIn("normal",function(){
						//Scroll the page down to view the new section
						$("body").scrollTo($(".section-"+$(this).data("nextPage")), 1000, { easing: 'easeOutQuad' });
						attachPopupFunctionality();
					});

					//If we've reached the total number of profiles then hide the show more button
					if($(".profile-list .profile").length>=$container.data("totalProfiles")){
						$(".show-more-button").css({visibility:'hidden'}).detach("click");
					}
				}
				else{
					callAjax($(".profile-list:last").data("sectionNum"),true);
				}
			}

			//Add a click event to show the next set of profiles
			$(".show-more-button").click(function(){
				showMore();
				return false;
			});

			//Function that given a section will trigger the preloading
			//of the next section behind the scenes
			function preloadSection($section)
			{
				//Preload the next section once all images have loaded
				var loadedCount = 0;
				var $profileImages = $section.find("li .profile img");
				$profileImages.load(function(){
					loadedCount++;
					//If all images have loaded
					if(loadedCount==$profileImages.length){
						callAjax($section.data("sectionNum"),false);
					}
				}).each(function(){
					if(this.complete){
						$(this).trigger("load");
					}
				});
			}

			function attachPopupFunctionality()
			{

				//Assume popup is consistent height/width and define the padding offset
				var popupHeight = 270;
				var popupWidth = 480;
				var paddingOffset = 20;

				//Attach functionality to each non-active profile
				$container.find(".profile-list li .profile:not('.active-profile'):visible").each(function (i) {
					var $this = $(this);

					//Indicate that the profile has interaction available by changing the pointer style and applying a class
					$this.css({cursor:"pointer"});
					$this.addClass("active-profile");
		   
					//Get the vital stats of each profile
					var thisWidth = $(this).width();
					var thisHeight = $(this).height();
					var thisLeft = $(this).position().left;
			
					//Initialise it's position
					var popupLeft = 0;
					var popupTop = 0;

					//Set left offset
					var leftOffset = thisLeft-(popupWidth/2)+(thisWidth/2);

					if( (leftOffset>0) && (leftOffset<(965-popupWidth)) )
					{
						popupLeft = -(popupWidth/2)+(thisWidth/2);
					}
					else if(leftOffset>(965-popupWidth)){
						popupLeft = thisWidth-popupWidth;
					}

					//Set top offset
					popupTop = -(popupHeight-thisHeight)/2; 

					//Account for padding
					popupTop-=paddingOffset;
					popupLeft-=paddingOffset;

					//Define the pop-up
					var $popup = $(this).find('.profile-popup');

					//Set the position of the popup
					$popup.css({left:popupLeft,top:popupTop,cursor:"default"});

					var hoverConfig =
					{
						over:function(){
							//Show the popup
							$popup.parent().css({"zIndex":"1000","overflow":"visible"});
							$popup.css({"zIndex":"2000","overflow":"visible"}).fadeIn();
						},
						out:function(){
							//Fade out the popup
							$popup.clearQueue();
							$popup.fadeOut(500,function(){
								$popup.css({opacity:1});
								$popup.parent().css("zIndex","0");
							});
						},
						sensitivity:2
					};

					$this.hoverIntent(hoverConfig);

					//Attach video popup functionality
					$popup.find(".profile-video").unbind("click").click(function(){
						//Get values of any padding/border on the popup (to determin offset)
						var padding = isNaN(parseInt($popup.css("padding-left").replace("px",""),10))?0:parseInt($popup.css("padding-left").replace("px",""),10);
						var border = isNaN(parseInt($popup.css("border-width").replace("px",""),10))?0:parseInt($popup.css("border-width").replace("px",""),10);
						
						//Get the absolute position and offset of the popup
						var topPositionRelativeToDocument = $popup.offset().top;
						var topRelativeOffset = -93 + padding + border;

						var leftPositionRelativeToDocument = $popup.offset().left;
						var leftRelativeOffset = padding + border;

						//Create the dialog and position it based on the positions calculate above
						var $videoPopup = $("<div id='video-popup'><iframe width='480' height='270' frameborder='0' src='"+this.href+"'></iframe></div>").dialog({modal:true,width:480,height:363,position:[0,0],close:function(){$videoPopup.fadeOut("fast",function(){$videoPopup.dialog('destroy').remove();})}});
						$videoPopup.parent().css({top:topPositionRelativeToDocument+topRelativeOffset,left:leftPositionRelativeToDocument+leftRelativeOffset});
						
						return false;
					});

					

				});
			}
		});
	};
})(jQuery);




/* News listing */
(function ($) {
	$.fn.newslisting = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}


		return $(this).each(function () {
			var numberOfListingsOnPage = $(".news-list .news-listing").length;
			var pageNum = getParameterByName("page")!=""?parseInt(getParameterByName("page"),10):1;
			var $container = $(this).parent().parent();
			var totalListings = 0;

			//Hide the pagination and output show more button
			$container.find(".pagination").hide().after("<a href='?page="+parseInt(pageNum+1)+"' class='show-more-button'>Show more news articles</a>");

			$(".show-more-button").click(function(){
				$.ajax({
					url: 'news/NewsListingAJAX.aspx?page='+parseInt(pageNum+1),
					success: function(data) {
						totalListings = totalListings==0?parseInt($(data).find("#listings-count").text(),10):totalListings;
						var $data = $(data).find("li.news-listing");        
						var $ul = $container.find("ul.news-list");
						$data.hide();

						if($data.length>0)
						{
							$ul.append($data);
							numberOfListingsOnPage = $(".news-list .news-listing").length;
							$ul.find("li:hidden").fadeIn("slow");
							$("body").scrollTo("#footer-container");
							pageNum++;
							if(numberOfListingsOnPage==totalListings){
								$(".show-more-button").css({visibility:'hidden'});
							}
						}

					}
				});
				return false;
			});
		});

	};
})(jQuery);


/* Featured story list plugin */
(function ($) {
	$.fn.featuredstorylink = function (options) {
		var settings = {};

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this);

			$this.find("li").each(function(i){
				var $storycontent = $(this).find(".story-content");
				var $h3 = $storycontent.find("h3");

				$storycontent.css({"cursor":"pointer"});
				//Check the slide has content (quirk with slider)
				if($storycontent.children().length>0)
				{
					var headingheight = $h3.height();
					$storycontent.css("top",108+19-headingheight); 
					var top = $storycontent.position().top;
					var boxheight = $storycontent.height();
					
					

					$(this).hover(function(){
						$storycontent.clearQueue();
						$storycontent.animate({top:(top-boxheight+headingheight)});
					},
					function(){
						$storycontent.clearQueue();
						$storycontent.animate({top:top});
					});

					$(this).click(function(){
						location.href = $h3.find("a").attr("href");
						return false;
					});
				}
			});
		});
	};
})(jQuery);

/* Events basket plugin */
(function ($) {
	$.fn.scrollWithPage = function (options) {
		var settings = {},
			$window = $(window);

		if (options) {
			$.extend(settings, options);
		}

		return $(this).each(function () {
			var $this = $(this),
				$parent = $(this).parent(),
				topOffset = $(".mid-content").height() + $(".mid-content").offset().top,
				offset = $(this).offset();

			//$parent.css("position","relative");
			
			$window.scroll(function(){
				var thisHeight = $this.height();

				//If the box isn't bigger than the viewport and needs to scroll
				//This prevents the box scrolling out of view
				if(thisHeight<$window.height() && $window.scrollTop() > offset.top)
				{
					console.log("topOffset",topOffset, "window scrolltop",$window.scrollTop(),"this height", thisHeight);
					console.log(topOffset-$window.scrollTop());
					if(topOffset-$window.scrollTop()-thisHeight-40>0)
					{
						$this.stop().animate({
							marginTop: $window.scrollTop() - offset.top + 8
						});
					}

				}
				else{
					$this.stop().animate({
						marginTop : 0
					});
				}

			});

		});
	};
})(jQuery);

$(document).ready(function () {

	//Open external links in a new window
	$("a[href^='http:']:not([href*='" + window.location.host + "'])").each(function () {
		$(this).attr("target", "_blank").addClass("external").click(function () { window.open(this.href); return false; });
	});

	//If the case study gallery exists attach click event, else hide the button
	if ($("#case-study-gallery").length > 0) {
		$(".lightbox-link").click(function () { $("#case-study-gallery").dialog('open'); return false; });
	}
	else {
		$(".lightbox-link").hide();
	}

	//Publication download lightbox: Phase 2
	/*
	$(".download-requires-reg").click(function () { 
	if($("#publicationId").length==0)
	{
	$("#publication-registration fieldset").after("<input type='hidden' id='publicationId' value='"+getParameterByNameFromString("publicationId",this.href)+"' />");
	}
	else{
	$("#publicationId").val(getParameterByNameFromString("publicationId",this.href));
	}
	$("#publication-registration").dialog('open');
	return false;
	});

	$("#publication-registration").dialog({
		autoOpen: false,
		modal: true,
		width: 570,
		position: ['center', 'top']
	});
	*/


	//Case study carousel
	function customiseCaseStudyCarousel() {
		var $csnext = $(".case-study-carousel .next_button").detach();
		var $csprev = $(".case-study-carousel .previous_button").detach();
		$(".case-study-carousel").prepend($csprev).append($csnext);
	}
	$(".case-study-carousel ul").ryslider({ contentElement: 'li', itemsToDisplay: 5, wrapSlider: true, renderPlayButton: false, renderStopButton: false, renderPageButtons: false, renderStateInfo: false, easingMethod: 'easeOutQuad', afterCreateFunction: customiseCaseStudyCarousel });

	//Main showcase/hero script
	function customiseShowcaseSlider() {

		if ($("#showcase-slider").length > 0) {
			$("#header-container").addClass("has-slideshow");
		}
		//wrap the pagination
		$(".page_container").wrap("<div class='page_container_wrap'/>");

		var $nextbutton = $("#showcase .next_button").detach();
		var $prevbutton = $("#showcase .previous_button").detach();

		$("#showcase .page_container_wrap").prepend($prevbutton).append($nextbutton);
		$("#showcase .page_container").wrap("<div class='page-scroll'/>");

		$("#showcase .page_container li:last").addClass("last");
		$("#showcase .page_container .page-1").addClass("active");

		var numberOfThumbs = $("#showcase .page_container li a").length;
		$("#showcase .page_container li a").each(function (i) {
			$(this).html($("#showcase-buttons li").eq(i).html());
			if(i==(numberOfThumbs-1))
			{
				var scrollerWidth = 0;
				var count = 0;
				var numberOfItems = $("#showcase .page_container li").length;

				$("#showcase .page_container li").each(function(j){
					scrollerWidth+=$(this).outerWidth(true);
					count++;
					if(j==(numberOfItems-1)){
				
						if(scrollerWidth>450){
							$("#showcase .page_container").width(scrollerWidth);
							$(".page-scroll").addClass("scrollable");
						}
					}
				});
			}
		});

		
		
		$("#showcase-buttons").remove();
		$(".slider_content").css({ overflow: 'hidden' });
		$(".slide-text").css("cursor", "pointer").click(function () { window.location = $(this).find("a:first").attr("href"); return false; });
		$("#showcase").hover(function () { $(".slide-text").clearQueue().animate({ top: '400px' }, 900, 'easeOutQuart'); }, function () { $(".slide-text").clearQueue().animate({ top: '480px' }, 900, 'easeOutQuart'); });
		
		//Attach Google Analytics Events
		$("#showcase .previous_button").click(function(){_gaq.push(['_trackEvent', 'Hero clicks', 'Clicked previous button']);});
		$("#showcase .next_button").click(function(){_gaq.push(['_trackEvent', 'Hero clicks', 'Clicked next button']);});
		$("#showcase .page_button").click(function(){_gaq.push(['_trackEvent', 'Hero clicks', 'Clicked page number '+$(this).attr("name"),$(this).find("img").attr("alt")]);});
	}
	function repositionPagingShowcase() {
		$(".scrollable").scrollTo(".page_container li a.active", 500,{easing: 'easeOutQuad',offset: {top:0, left:-100} });
	}
	//Only apply the slider if we have more than one slide
	if($("#showcase-slider>div").length>1)
	{
		$("#showcase-slider").ryslider({ renderPlayButton: false, renderStopButton: false, wrapSlider: true, afterCreateFunction: customiseShowcaseSlider, afterSlideFunction: repositionPagingShowcase });
	}
	//Gallery slider
	function customiseGallery() {
		$(".gallery .page_container").wrap("<div class='page_container_wrap'/>");
		$nextbutton = $(".gallery .next_button").detach();
		$prevbutton = $(".gallery .previous_button").detach();
		$(".gallery .page_container_wrap").prepend($prevbutton).prepend($nextbutton);

		$(".gallery .page_container li:last").addClass("last");
		$(".gallery .page_container .page-1").addClass("active");
		$(".gallery .page_container li a").each(function (i) {
			$(this).html($("#gallery-buttons li").eq(i).html());
		});
		$(".slider_content").css({ overflow: 'hidden' });

		var calculatedWidth = $("#case-study-gallery .page_container li").eq(0).outerWidth(true) * $("#case-study-gallery .page_container li").length;
		if (calculatedWidth > 750) {
			$(".gallery .page_container").wrap("<div class='page_container_scroll'/>").css("float", "none");
			$(".gallery .page_container").width(calculatedWidth);
		}
		else {
			$(".gallery .page_container").width(calculatedWidth).css("float", "none");
		}
	}
	function repositionPaging() {
		$(".page_container_scroll").scrollTo(".page_container li a.active", 500,{easing: 'easeOutQuad',offset: {top:0, left:-300} });
		
		//If an iframe has been marked for removal then detach and reattach
		$("iframe.removeMe").each(function () {
			this.src = this.src;
		}).removeClass("removeMe");
	}
	function galleryBeforeSlide() {
		//If we're on an iframe slide then we need to make sure it's reattached after sliding (to stop video playback)
		$(".gallery .slides .active iframe").addClass("removeMe");
	}
	
	if ($(".gallery").length > 0) {
		$(".gallery").dialog(
		{
			autoOpen: true,
			modal: true,
			width: 900,
			position: ['center', 'top'],
			open: function (event, ui) {
				if (!$(".gallery ul").hasClass("ryslider")) {
					$(".gallery ul").ryslider({ enablePlayStop: false, wrapSlider: true, contentElement: 'li', afterCreateFunction: customiseGallery, beforeSlideFunction: galleryBeforeSlide, afterSlideFunction: repositionPaging });
				}
			}
		}).dialog('close');

		//remove any click event before assigning new click event
		$("a[class*='gallery-item']").unbind('click');
		$("a[class*='gallery-item']").click(function () {
			var id = parseInt($(this).attr("class").split("gallery-item-")[1], 10);
			$("#case-study-gallery").dialog('open');
			$(".gallery ul li a").eq(id - 1).click();
			return false;
		});
	}

	$(".map-link").hover(function () { $(this).find("span").clearQueue().animate({ bottom: '0' }); }, function () { $(this).find("span").clearQueue().animate({ bottom: '-32px' }); });



	//Attach scroll with page functionality
	$(".events-basket").scrollWithPage();

	//Attach lightbox video functionality
	$(".richtext-video-module a").lightboxvideo();

	//Attach footer functionality
	$("#footer-container").footerActivate();

	//Attach watermark functionality
	$(".watermarked").watermark();

	//Attach featured story link functionality
	$(".featured-story-list,.case-study-carousel").featuredstorylink();

	//Attach profile functionality
	$("#profiles").interactiveprofile();

	//Attach news listing functionality
	$(".news-list").newslisting();

	//Attach subscribe to newsletter functionality
	$(".subscribe").subscribeNewsletter();

	//Attach form validation functionality
	$(".form").formValidation();

	//Attach events basket functionality
	$(".events-list").eventsbasket();

	//Print blog page  functionality
	$(".print-link").live('click', function(e){
		window.print();
		e.preventDefault();
	});
});
