/*
	Author: Joe Critchley
	Motionlab Marketing Ltd. www.motionlab.co.uk
*/

(function($) {
	
	$('body').removeClass('unloaded').addClass('loaded');
	
	/**
	 * UNDEFINED >-)
	 */
	
	var undefined;
	
	$('body').prepend('<div id="simpletooltip"></div>');
		
	/**
	 * Custom universal easing.
	 */
	
	$.easing.custom = function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	};
	
	/**
	 * IE6 Upgrade Message
	 */
	 
	if(($.browser.msie && $.browser.version == '6.0')) {
		$('body').prepend("<div style='border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative;'><div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:this.parentNode.parentNode.style.display=\"none\"; return false;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/></a></div>    <div style='width: 640px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>      <div style='width: 75px; float: left;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div>      <div style='width: 275px; float: left; font-family: Arial, sans-serif;'>        <div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>You are using an outdated browser</div>        <div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>For a better experience using this site, please upgrade to a modern web browser.</div>      </div>      <div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div>      <div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div>      <div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div><div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div></div></div>");
	}

	/**
	 * Fix IE6 PNGs
	 */
	 
	if(typeof DD_belatedPNG != 'undefined') {
		DD_belatedPNG.fix('.png_bg');
		DD_belatedPNG.fix('#container');
		DD_belatedPNG.fix('#footnotes');
		DD_belatedPNG.fix('.primary_cta span');
		DD_belatedPNG.fix('.cta span');
		DD_belatedPNG.fix('.title_box');
		DD_belatedPNG.fix('.caption');
		DD_belatedPNG.fix('.related_banner img');
		DD_belatedPNG.fix('#main_nav span');
		DD_belatedPNG.fix('#main_nav ul');
	}

	/**
	 * Inset Borders on listing images
	 */
	
	/* if(!$.browser.webkit) {
		$('.listing:not(.disable_links) .listing_image img, .landing_block_images .landing_image img, .border').insetBorder({
			borderColor: '#ffffff',
			insetleft : 5,
			insetright : 5,
			insettop : 5,
			insetbottom : 5
		});
	} */
		
	/**
	 * Reverse stack the vertical tabs.
	 */
	
	$('.reverse_stack').each(function() {
		var __childLength = $(this).children().length;
		$(this).children().each(function() {	
			$(this).css('zIndex', __childLength);
			__childLength--;
		});
	});
	
	/**
	 * Event handling on search box.
	 */
	 
	 var $search_box = $('.search_box');
	 var $input = $search_box.find('input');
	 
	 $search_box.bind('click', function() {
	 	$input.trigger('focus');
	 });
	 
	 $input.bind('focus', function() {
	 	$search_box.addClass('on');
	 }).bind('blur', function() {
	 	$search_box.removeClass('on');
	 });
	 
	 /**
	  * Effect bubbling for hit areas.
	  */
	  
	 $('.bubble_to').livequery(function() {
	 	var hover_its = $(this).find('.hover_it');
	 	hover_its.hover(function() {
	 		return false;
	 	}, function() {
	 		return false;
	 	});
	 	$(this).hover(function() {
	 		hover_its.trigger('mouseenter');
	 	}, function() {
	 		hover_its.trigger('mouseleave');
	 	}).click(function() {
	 		var _anchor = $(this).find('.bubble_from').eq(0);
	 		var _location = _anchor.attr('href') || '#';
	 		if(_location == '#') {
	 			_anchor.trigger('click');
	 		}
	 		else {
	 			window.location = _location;
	 		}
	 	});
	 });
	 
	 /** 
	 * Form styling
	 */
	 var main_forms = $('.main_form');
	 if(main_forms.length) {
	 	
	 	main_forms.each(function() {
	 		var form = $(this);
	 		form.find('input,select,textarea').each(function() {
	 			var input = $(this);
	 			var field = $(this).closest('.field');
	 			$(this).focus(function() {
	 				field.addClass('focus');
	 			}).blur(function() {
	 				field.removeClass('focus');
	 			});
	 		});
	 	});
	 	
	 }
	 
	 /**
	  * Case Studies, DOM Injection.
	  */
	 
	 var case_studies = $('.case_studies_pres');
	 if(case_studies.length && !($.browser.msie && $.browser.version == '6.0')) {

	 	case_studies.find('h2 a').bind('click', function(e) {
	 		
	 		e.preventDefault();
	 		
	 		var __url = $(this).attr('href');
	 		
	 		var current = false;
	 		if($(this).parent('h2').hasClass('current')) {
	 			current = true;
	 		}
	 		
	 		if(__url) {
	 			
	 			$(case_studies).find('.accordion_content').slideUp(function() {
	 				$(this).remove();	
	 			});
	 			
	 			
	 			case_studies.find('h2').removeClass('current');
	 			
	 			
	 			if(current) {
	 				return;
	 			}
	 			
	 			var __html = '<div class="accordion_content" style="display: none"></div>';
	 			$(this).parent('h2').after(__html).addClass('current');
	
	 			var __accordion_content = $(this).parent('h2').next('.accordion_content');

	 			var href_no_hash = $(this).attr('href').substr(0,$(this).attr('href').indexOf('#'))
	 		
	 			__accordion_content.load(href_no_hash + ' #' + $(this).parent('h2').attr('id') + '_inner', function(data) {
	 				__accordion_content.find('ul').unwrap('<div class="accordion_content"></div>');
	 				__accordion_content.slideDown();
	 			});
	 			
	 		}
	 		
	 	});
	 
	 }
	 
	 /**
	  * Share
	  */
	  
	$('iframe').attr('frameborder', '0');
	
	 
	
	
	
		
	
	/**
	 * Vertical tabs.
	 */
	
	var vertical_tab_content = $('.vertical_tabs a');
	vertical_tab_content.click(function(e) {
		
		vertical_tab_content.closest('.vertical_tabs').next('.vertical_tab_content').find('.item').hide();

		$($(this).attr('href')).show();
				
		vertical_tab_content.parent('li').removeClass('current');
		$(this).parent('li').addClass('current');
		e.preventDefault();
		
	}).filter(':first').trigger('click');
	
	/**
	 * Blockquotes
	 * -- append an empty span to the end of each quote to allow for easier styling.
	 */
	 
	$('blockquote').each(function() {
		$(this).find('p:last').append('<span>&nbsp;</span>')
	});
	
	/**
	 * Cycle Slideshows
	 */
	
	var detail_slideshow = $('.detail_slideshow');
	if(detail_slideshow.length && $.fn.cycle != undefined) {
	
		detail_slideshow.cycle({
			timeout: 3000
		});
	
	}
	
	
	
	/**
	 * Curtains Gallery
	 */
	
	var carousel_container = $('.carousel_container');

	if(carousel_container.length) { 
		
		var detailsToChange = $('[data-cacheref]');
		var disabled = false;
		var carouselSize = parseInt(carousel_container.attr('data-carouselsize'));
			 
		carousel_container.scrollable({
			easing: 'custom',
			speed: 600,
			prev: '.prev',
			next: '.next',
			history: true
		});
		
		var carousel_api = carousel_container.data('scrollable');
		
		$(carousel_container).find('.prevNext').click(function(e) {
			e.preventDefault();
		});
		
		var carousel_li = carousel_container.find('li');

		var savedHash = '';
		
		$('.prevNext').click(function(e) {	
			e.preventDefault();
		});
		
		carousel_li.click(function(e) {
			
			var self = $(this);
			
			var prevCurrent = self.closest('.inner').find('li.current');

			e.preventDefault();
			
			if(galleryCache == undefined || disabled === true) {
				return;
			}
				
			// activate item
			carousel_li.removeClass("current");
			self.addClass("current");
			
			var offset = self.parent('ul').index() * carouselSize;
			var fabricDetail = galleryCache[parseInt(self.attr('data-index'))];
			
			var fabricImages = [];

			// change fabric details
			detailsToChange.each(function(k, v) {
			
				var cacheRef = $(this).attr('data-cacheref');
				var cacheType = $(this).attr('data-cachetype');
				
				switch(cacheType) {
					
					case 'src':
					
						var fab = $(this);
						fab.fadeOut(200, function() {
							if(!fabricDetail[cacheRef]) {
								fabricDetail[cacheRef] = 'blank.gif';
							}
							if( '/'+fabricDetail[cacheRef] == $(this).attr('src') || fabricDetail[cacheRef] == $(this).attr('src')) {
								$(this).fadeIn(200);
							}
							else {
								$(this).attr('src', '/'+fabricDetail[cacheRef]);
								this.onload = function() {
									$(this).fadeIn(200);
								};
							}
						});
						
					break;
					
					case 'src_swipe':
					
						disabled = true;
						
						var fab = $(this);
						var fabWidth = $(this).width();
						var fabDirection;
						
						// Reverse it in case it needs to look like its going backwards.
					
						if(parseInt(prevCurrent.attr('data-index')) > parseInt(self.attr('data-index'))) {
							fabDirection = fabWidth * -1;
						}
						else {
							fabDirection = fabWidth;
						}
					
						fab.animate({
							left: (fabDirection * -1)
						}, {
							easing: 'easeInBack',
							duration: 400,
							complete: function() {
								
								if(!fabricDetail[cacheRef]) {
									fabricDetail[cacheRef] = 'blank.gif';
								}
								
								var onComplete = function() {
									fab.hide();
									fab.animate({
										left: fabDirection
									}, {
										duration: 100,
										easing: 'linear',
										complete: function() {
											fab.show();
											fab.animate({
												left: '0px'
											}, {
												duration: 400,
												easing: 'easeOutBack',
												complete: function() {
													disabled = false;
												}
											});
										}
									});
								}
								
								// No point swapping if it's the same image.
								if( '/'+fabricDetail[cacheRef] == $(this).attr('src') || fabricDetail[cacheRef] == $(this).attr('src')) {
									onComplete();
								}
								else {
									$(this).attr('src', '/'+fabricDetail[cacheRef]);
									this.onload = function() {
										onComplete();
									};
								}
								
							}
						});
						
					break;
					
					case 'html':
						
						
				
						$(this).html(fabricDetail[cacheRef]);
						
					break;
					
					case 'title':
						
						if(!fabricDetail[cacheRef]) {
							fabricDetail[cacheRef] = ' ';
						}
						
						$(this).attr('data-title', fabricDetail[cacheRef]);
						
						$(this).simpletooltip();
										
					break;
					
					case 'href':
					
						$(this).attr('href', fabricDetail[cacheRef]);
						
					break;
				
				
				}
				
			});
			
			return false;
			
		});
		
		carousel_li.find('a').history(function(event, hash) {
			
			if(disabled === true) {
				return;
			}
			
			if(hash) {
				carousel_li.removeClass('current');
				savedHash = hash.replace(new RegExp("#", "gi"), '');
				$('a[href="' + savedHash + '"]').parent('li').addClass('current');
			}
			
			carousel_li.filter('.current').eq(0).trigger('click');
		
			carousel_container.find('ul:not(.cloned)').each(function() {
				var current_li = $(this).find('li.current');
				if(current_li.length) {
					carousel_api.seekTo(current_li.parent('ul').index(), 300);
					return false;
				}
			});
		
			return false;
			
		});
		
	}
	
	 
	/**
	 * CSE Search Results
	 */ 
	
	var search_results = $('#cse-search-results');
	if(search_results.length) {
		search_results.find('> iframe').width('100%');
	}
	
	/**
	 * Main nav
	 */
	 
	var menu = $('#main_nav');
	
	if(menu.length && (!$.browser.msie || ($.browser.msie && parseInt($.browser.version) >= 9))) {
		
		/*
		menu.find('li.parent > a').click(function(e) {
			e.preventDefault();
			showNav($(this).parent('li'));
		});
		*/
		
		var firstClick = true;
		
		function showNav(li) {
			
			if(li.hasClass('on')) {
				li.removeClass('on').find('ul').fadeOut(300);
			}
			else {
				// fade out others
				menu.find('li.parent').removeClass('on');
				menu.find('li.parent').find('ul').fadeOut(300);
				
				// fade in 
				
				li.addClass('on').find('ul').fadeIn(300).css({'zIndex':10000});
				$('.nav').css({'z-index':10000});
			}
			
		}
		
		menu.hoverIntent({
			over: function() {
				// empty
			},
			out: function() {
				firstClick = true;
			}
		});
		
		if(Modernizr != undefined && Modernizr.touch) {
			
			menu.find('> nav > ul > li').bind('touchend', function(e) {
				e.preventDefault();
				var li = $(this);
				if(li.find('ul').is(':hidden')) {
					showNav($(this));
				}
				else {
					var li = $(this);
					if(li.hasClass('on') && li.hasClass('parent')) {
						li.removeClass('on').find('ul').fadeOut(300);
					}
				}
			});
			
			menu.find('> nav > ul > li.parent > a').click(function() {
				return false;
			});
		
		}
		else {	
				
			menu.find('> nav > ul > li').hoverIntent({
				over: function() {
					showNav($(this));
				},
				timeout: 500,
				out: function() {
					var li = $(this);
					if(li.hasClass('on') && li.hasClass('parent')) {
						li.removeClass('on').find('ul').fadeOut(300);
					}
				}
			});
		
		}

	}
	
	
	/**
	 * Tooltips
	 */
	
	var tooltip_triggers = $(".tooltip_trigger[title]");
	
	if(tooltip_triggers.length) {
		
		$('body').prepend('<div class="tooltip"></div>');
		
		tooltip_triggers.tooltip({
			tip: '.tooltip',
			effect: 'fade',
			fadeOutSpeed: 100,
			predelay: 100,
			position: "bottom right",
			offset: [-20, -40]
		});
		
		var tooltip_api = tooltip_triggers.data('tooltip');
				
		tooltip_api.onBeforeShow(function(e, pos) {
			
			if(this.getTrigger().attr('data-title')) {
			
				var tip = this.getTip();
				var title_value = this.getTrigger().attr('data-title');
				tip.html(title_value);
			
			}
			
		});

	}
	
	 
})(jQuery);


// Uses window.load instead of document.ready due to a Webkit bug.
$(window).load(function() {
	
	/**
	 * Overlays
	 */
	
	var overlay_triggers = $('.overlay_trigger[rel]'); 
	 
	if(overlay_triggers.length) { 
	 
	 	overlay_triggers.overlay({
			effect: 'apple'
		});
		
		var overlay_api = overlay_triggers.data('overlay');
		
		overlay_api.onBeforeClose(function() {
			var iframe = overlay_api.getOverlay().find('iframe');
			iframe.attr('src', '').attr('data-src', 'http://www.youtube.com/embed/LnhYEAwba2I');
		});
		
		overlay_api.onBeforeLoad(function() {
			var iframe = overlay_api.getOverlay().find('iframe');
			if(!iframe.attr('src') && iframe.attr('data-src')) {
				iframe.attr('src', 'http://www.youtube.com/embed/LnhYEAwba2I');
			}
		});
		
	}
	
	/** 
	 * Carousel-style slideshows
	 */
	
	$('.slide_container').livequery(function() {
		
		var slide_container = $(this);
		var step_nav = $(this).prev('.step_nav');
		var newDate = new Date();
		var id = newDate.getTime() + '_' + Math.floor(Math.random()*11);
		step_nav.attr('id', id);
		slide_container.scrollable({
			easing: 'custom',
			speed: 600
		}).navigator({
			navi: '#'+id,
			activeClass: 'current'
		});
		
		step_nav.find('a:first').trigger('click');
		
		var api = slide_container.data('scrollable');
		
		$(this).find('.primary_cta').click(function(e) {
			api.next();
			e.preventDefault();
		});
				
		var _height = $(this).find('.slide img').height();
		$(this).height(_height);
		$(this).find('.inner, .slide').height(_height);
		
	});
	
	$('.step_nav li.current').livequery(function() {
		$('.step_nav li.next').removeClass('next');
		$(this).next('li').addClass('next');
	});
	
	/** 
	 * Fix for IE scrolling issue on gallery. 
	 */
	
	if($('.gallery_main').length) {
		window.scrollTo(0,0);
	}

	
});

jQuery(document).ready(function() {
						
						jQuery('.find_address').bind('click', function() { findPostCode(); return false; } )
						jQuery('#cnt_Postcode').bind('click', function() { jQuery('.address_match_list').hide() } );
						jQuery('.enter_manually').bind('click', function() { enterManually(this); return false; } );
				//	
					 })
					 
					 function enterManually(section)
					{
						$section = jQuery(section).parent().parent();
						if(jQuery($section).is('fieldset') || jQuery($section).is('.fieldset'))
						{
							
						}
						else
						{
							$section = jQuery(section).parent().parent().parent();
						}
						jQuery('.addressField',jQuery($section)).show();
					
					}

					 function findPostCode()
					 {
					 	
						if(jQuery('#cnt_Postcode').val() == '')
						{
							alert('No PostCode');
						}	
						else
						{
							var reg = new RegExp("^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]{1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$");
							$check = reg.test(jQuery("#cnt_Postcode").val().toUpperCase().replace(/ /gi,''));
							if($check)
							{
								if(jQuery('#cnt_House_Number').val() == '')
								{
									var html = jQuery.ajax({ 
										type: "POST",
										url: '/includes/postCodeLookup.php?getList',
										async: false,
										data: {'postCode' : jQuery('#cnt_Postcode').val() }	
									}).responseText;	
									
									if(html != 'error')
									{
										eval('list = ' + html);
										jQuery('li', jQuery('.address_match_list')).remove();
										jQuery(list).each(function(key, value) { 
											if(jQuery(".address_match_list li").length > 0)
											{
												jQuery(".address_match_list li:last").append('<li><a href="" id="'+value['Id']+'">'+value['StreetAddress']+'</a></li>');
											}
											else
											{
												jQuery(".address_match_list ").append('<li><a href="" id="'+value['Id']+'">'+value['StreetAddress']+'</a></li>');
											}
										} );
										jQuery('.address_match_list').show();
										jQuery('.address_match_list li a').bind('click',function() { getAddress(jQuery(this).attr('id')); return false; } )
									}
									else
									{	
										alert('The postcode you entered was not found');
									}
									
								}
								else
								{
								/*	var html = jQuery.ajax({ 
										type: "POST",
										url: '/includes/postCodeLookup.php?findNumberPostcode',
										async: false,
										data: {'postCode' : jQuery('#cnt_Postcode').val(), 'building': jQuery('#cnt_House_Number').val() }	
									}).responseText;	
									
									if(html != 'error')
									{
										eval('theData = ' + html);
										jQuery('#cnt_Street').val(theData[0]['PrimaryStreet']);
										jQuery('#cnt_TownCity').val(theData[0]['PostTown']);
										jQuery('.addressField').show();
										//jQuery('#county').val(theData[0]['County']);
									}*/
								}
							}
							else
							{
								alert('The postcode you entered does not seem to be valid');	
							}
						}
					 }
				
					function getAddress($address)
					{
						jQuery('.address_match_list').hide();
					
							var html = jQuery.ajax({ 
								type: "POST",
								url: '/includes/postCodeLookup.php?findAddress',
								async: false,
								data: {'id' : $address }	
							}).responseText;	
							
							if(html != 'error')
							{
								eval('theData = ' + html);
								$houseNumName = (theData[0]['BuildingNumber'] != '') ? theData[0]['BuildingNumber'] : theData[0]['BuildingName'];
								jQuery('#cnt_House_Number').val($houseNumName);
							
								jQuery('#cnt_Street').val(theData[0]['PrimaryStreet']);
								jQuery('#cnt_TownCity').val(theData[0]['PostTown']);
								jQuery('.addressField').show();
								//jQuery('#county').val(theData[0]['County']);
							}
					}
