/*****************************Scroll to Hashes************************/
function hashScroll() {
	var hash = window.location.hash;
	
	if(hash && $(hash).length > 0) {

		var hashTop = $(hash).offset().top;

		$('html, body').animate({
			scrollTop: hashTop
		}, 600);
	}
}

/*****************************Jump Links************************/
function jumpLinks() {
	
	$('.jump_links a').click(function(event) {
		event.preventDefault();
		// set target id var based on link href
		var jumpTarget = $(this).attr('href');
		
		if($(jumpTarget).length > 0) { // If we have a target var
			var jumpHeight = $(jumpTarget).offset().top; // calculate distance we need to scroll
			$('html, body').animate({
				scrollTop: jumpHeight // scroll to target
			}, 400);
			// add hash to url
			window.location.hash = jumpTarget;
		}
		return false;
	});
	
	// Scroll to top of page
	$('.jump_to_top').click(function(event) {
		event.preventDefault();
		$('html, body').animate({
			scrollTop: 0
		}, 400);
		// add hash to url
		window.location.hash.remove;
		return false;
	});
}

/*****************************Print page tool************************/
function printAction() {
	var printLink = $('#page_actions .print');
	printLink.click(function() {
		window.print();
	});
}

/*****************************Open 'external' links in new window/tab************************/
function externalLinks() {
	var link = $('a.external');
	link.click(function() {
		window.open(this.href);
		return false;
	});
}

/*****************************Full-Bleeder************************/
function fullBleeder(target, minHeight) {
	// grab initial dimensions
	var initialWidth = target.width();
	var initialHeight = target.height();
	
	// calculate aspect ratio 
	var targetRatio = initialHeight / initialWidth;
	
	
	function fullBleedIt() {
		var winWidth = $(window).width();
	
		var minWidth = minHeight / targetRatio; // minWidth is our passed minHeight variable, divided by the target's ratio
		
		if(winWidth <= minWidth) { // If the current window width is going to scale our target too small
			target.css('width',minWidth); // Set the width to minWidth, which is the passed minHeight var divided by the target's aspect ratio
			target.css('height',minHeight); // Set the height to the passed minHeight value
		} else {
			target.css('width',winWidth); // Set the target's width to that of the window
			target.css('height',winWidth * targetRatio); // Set the height to the window's width * our target's aspect ratio
		}

	}
	
	fullBleedIt();
	
	// Fire on window resize
	$(window).resize(fullBleedIt);
}

/*****************************Home Carousel************************/
function homeCarousel() {
	var carouselContainer = $('#home_carousel');
	var carouselSlide = $('#home_carousel .slide');
	var carouselImage = $('#home_carousel #carousel_images img');
	var carouselOverlay = $('#home_carousel #carousel_overlay');
	
	var carouselPrev = $('#home_carousel #carousel_prev');
	var carouselNext = $('#home_carousel #carousel_next');
	
	var carouselNav = $('#home_carousel #carousel_nav li');
	
	var slidesTotal = carouselNav.size() - 1;
	
	var activeSlideIndex = 0;
	var intervalCounter = 0;
	
	var intervalBlocked = false;
	
	fullBleeder(carouselImage, '680');
	
	// Add active classes to first slide, image, nav item
	carouselSlide.eq(0).addClass('active');
	carouselImage.eq(0).addClass('active');
	carouselNav.eq(0).addClass('active').addClass('first');
	
	// Sets Container and Overlay heights to match fullBleedered images
	function matchHeights() {
		var currentHeight = carouselImage.css('height');
		carouselContainer.css('height',currentHeight);
		carouselOverlay.css('height',currentHeight);
	}
	
	matchHeights();
	
	// Fire on window resize
	$(window).resize(matchHeights);
	
	
	// Updates inactive carousel objects off-stage
	function updateInactives() {
		// Offset inactive slides by their current width		
		carouselSlide.each(function() {
			if(!$(this).hasClass('active')){
				$(this).css('left', '-' + $(window).width() + 'px');
			}
		});
		
		// Offset inactive images by their current width		
		carouselImage.each(function() {
			if(!$(this).hasClass('active')){
				$(this).css('left', '-' + $(this).width() + 'px');
			}
		});
	}
	updateInactives();
	// Fire on window resize
	$(window).resize(updateInactives);
	
	function updatecarouselNav() {
		carouselNav.removeClass('active');
		carouselNav.eq(activeSlideIndex).addClass('active');
	}
	
	// All of the slide/image animation gubbins
	function changeSlide(fromDirection) {
		if(fromDirection == 'right') {
			// Animate old slide out
			$('#home_carousel .slide.active').animate({
				left: '-=460px'
			}, 1000, 'easeOutExpo');
		
			// Animate active slide across
			carouselSlide.eq(activeSlideIndex).css('left', '460px').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselSlide.removeClass('active');
				$(this).addClass('active');
				updateInactives();
			});
		
			// Animate old image out
			$('#home_carousel #carousel_images img.active').css('z-index','1').animate({
				left: '-=' + $(this).width()
			}, 1000, 'easeOutExpo');
		
			// Animate active image across
			carouselImage.eq(activeSlideIndex).css('left',$(window).width()).css('z-index','2').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselImage.removeClass('active');
				$(this).addClass('active');
				updateInactives();
			});
		} else {
			// Animate old slide out
			$('#home_carousel .slide.active').animate({
				left: '+=460px'
			}, 1000, 'easeOutExpo');

			// Animate active slide across
			carouselSlide.eq(activeSlideIndex).css('left', '-460px').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselSlide.removeClass('active');
				$(this).addClass('active');
				updateInactives();
			});
		
			// Animate old image out
			$('#home_carousel #carousel_images img.active').css('z-index','1').animate({
				left: '+=' + $(this).width()
			}, 1000, 'easeOutExpo');
		
			// Animate active image across
			carouselImage.eq(activeSlideIndex).css('left', '-' + $(window).width()).css('z-index','2').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselImage.removeClass('active');
				$(this).addClass('active');
				updateInactives();
			});
		}

		// Update active carousel nav item
		carouselNav.removeClass('active');
		carouselNav.eq(activeSlideIndex).addClass('active');
		
	}
	
	// carousel Controls (arrows) interaction
	carouselNext.click(function() {
		if(!carouselSlide.is(':animated')) {

			if(activeSlideIndex == slidesTotal) {
				activeSlideIndex = 0;
			} else {
				activeSlideIndex += 1;
			}
		
			changeSlide('right');
			intervalBlocked = true;
			clearInterval(intervalChange)
		}
		
		return false;
	});
	
	
	carouselPrev.click(function() {
		if(!carouselSlide.is(':animated')) {	
		
			if(activeSlideIndex === 0) {
				activeSlideIndex = slidesTotal;
			} else {
				activeSlideIndex -= 1;
			}
		
			changeSlide('left');
			intervalBlocked = true;
			clearInterval(intervalChange)
		}
		
		return false;
		
	});
	
	// carousel Nav (unordered list) Interaction
	carouselNav.click(function() {
		var direction;
		if(!carouselSlide.is(':animated')) {
			if(activeSlideIndex !== carouselNav.index($(this))) {
				if(activeSlideIndex > carouselNav.index($(this))) {
					direction = 'left';
				} else {
					direction = 'right';
				}
				activeSlideIndex = carouselNav.index($(this));
				
				changeSlide(direction);
				intervalBlocked = true;
				clearInterval(intervalChange);
			}
		}
		return false;
	});
	
	var intervalChange;
	
	// Cycle through all slides once and then back to slide 1
	function intervalFirerer() {
		
		
		if(!carouselSlide.is(':animated')) {
			intervalCounter++;

			if(activeSlideIndex == slidesTotal) {
				activeSlideIndex = 0;
			} else {
				activeSlideIndex += 1;
			}
		
			changeSlide('right');
		}
		
		if(intervalCounter > (slidesTotal)) {
			clearInterval(intervalChange);
		}
	}
	
	function initialIntervalSet() {
		if(intervalBlocked != true) {
			intervalChange = setInterval(intervalFirerer, 8000);
		}
	}
	
	var initialIntervalSetter = setTimeout(initialIntervalSet, 4000);
}



/*****************************Landing Page Carousel************************/
function landingCarousel() {
	var carouselContainer = $('#landing_carousel');
	var carouselSlide = $('#landing_carousel .slide');
	var carouselImage = $('#landing_carousel #carousel_images img');
	
	var carouselNav = $('#landing_carousel #carousel_nav li');
	
	var slidesTotal = carouselNav.size() - 1;
	
	var activeSlideIndex = 0;
	var intervalCounter = 0;
	
	var intervalBlocked = false;
	
	// Add active classes to first slide, image, nav item
	carouselSlide.eq(0).addClass('active');
	carouselImage.eq(0).addClass('active');
	carouselNav.eq(0).addClass('active').addClass('first');
	
	
	function updatecarouselNav() {
		carouselNav.removeClass('active');
		carouselNav.eq(activeSlideIndex).addClass('active');
	}
	
	// All of the slide/image animation gubbins
	function changeSlide(fromDirection) {
		if(fromDirection == 'right') {
			// Animate old slide out
			$('#landing_carousel .slide.active').animate({
				left: '-=460px'
			}, 1000, 'easeOutExpo');
		
			// Animate active slide across
			carouselSlide.eq(activeSlideIndex).css('left', '460px').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselSlide.removeClass('active');
				$(this).addClass('active');
			});
		
			// Animate old image out
			$('#landing_carousel #carousel_images img.active').css('z-index','1').animate({
				left: '-=940px'
			}, 1000, 'easeOutExpo');
		
			// Animate active image across
			carouselImage.eq(activeSlideIndex).css('left','940px').css('z-index','2').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselImage.removeClass('active');
				$(this).addClass('active');
			});
		} else {
			// Animate old slide out
			$('#landing_carousel .slide.active').animate({
				left: '+=460px'
			}, 1000, 'easeOutExpo');
		
			// Animate active slide across
			carouselSlide.eq(activeSlideIndex).css('left', '-460px').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselSlide.removeClass('active');
				$(this).addClass('active');
			});
		
			// Animate old image out
			$('#landing_carousel #carousel_images img.active').animate({
				left: '+=940px'
			}, 1000, 'easeOutExpo');
		
			// Animate active image across
			carouselImage.eq(activeSlideIndex).css('left', '-940px').animate({
				left: 0
			}, 1000, 'easeOutExpo', function() {
				carouselImage.removeClass('active');
				$(this).addClass('active');
			});
		}
		// Update active carousel nav item
		carouselNav.removeClass('active');
		carouselNav.eq(activeSlideIndex).addClass('active');
		
	}
	
	// carousel Nav (unordered list) Interaction
	carouselNav.click(function() {
		var direction;
		if(!carouselSlide.is(':animated')) {
			if(activeSlideIndex !== carouselNav.index($(this))) {
				if(activeSlideIndex > carouselNav.index($(this))) {
					direction = 'left';
				} else {
					direction = 'right';
				}
				activeSlideIndex = carouselNav.index($(this));
				
				changeSlide(direction);
				intervalBlocked = true;
				clearInterval(intervalChange);
			
			}
		}
		return false;
	});
	
	
	
	var intervalChange;
	
	// Cycle through all slides once and then back to slide 1 
	function intervalFirerer() {
		
		
		if(!carouselSlide.is(':animated')) {
			intervalCounter++;

			if(activeSlideIndex == slidesTotal) {
				activeSlideIndex = 0;
			} else {
				activeSlideIndex += 1;
			}
		
			changeSlide('right');
		}
		
		if(intervalCounter > (slidesTotal)) {
			clearInterval(intervalChange);
		}
	}
	
	function initialIntervalSet() {
		if(intervalBlocked != true) {
			intervalChange = setInterval(intervalFirerer, 8000);
		}
	}
	
	var initialIntervalSetter = setTimeout(initialIntervalSet, 4000);
	
}




/*****************************Site Search************************/
function siteSearch() {
	var searchForm = $('#searchform');
	var searchInput = $('#searchform #s');
	
	searchInput.focus(function() {
		searchForm.addClass('focused');
	});
	
	searchInput.blur(function() {
		searchForm.removeClass('focused');
	});
	
	// Prevent empty form submission
	searchForm.submit(function() {
		if (searchInput.val() === "") {
			return false;
		}
	});
}

/*****************************.last Class************************/
function lastClass() {
	$('ul').each(function() {
		// Apply .last class to last list item in each list
		$(this).find('li:last').addClass('last');
	});
	
	$('dl').each(function() {
		// Apply .last class to last list item in each list
		$(this).find('dd:last').addClass('last');
	});
}


/*****************************Filters Nav Interaction************************/
function filtersNav() {
	var navItems = $('#nav_filters > li.filter');
	var timedNavHideActive = false;
	var timedNavHide;
	
	navItems.hover(function() {
		navItems.removeClass('active'); // remove any active classes from nav items
		$(this).addClass('active'); // add active class to active nav item
		
		// Clear subnav hide timeout when new nav item is moused-over
		if(timedNavHideActive === true) {
			clearTimeout(timedNavHide);
			timedNavHideActive = false;
		}
		
		return false;
	}, function() {
		timedNavHideActive = true; // var to say timeout is active
		
		// Set subnav hide timout on mouseout
		timedNavHide = setTimeout(function() {
		    navItems.removeClass('active'); // remove any active classes from nav items
			timedNavHideActive = false; // reset timout var
	    }, 800);
	    
	    return false;
	});

}

/*****************************Project Grid************************/
function projectGridInteraction() {
	var gridTitle = $('#grid_title');
	
	var projectGrid = $('#project_grid');
	var activeProjectSlidesContainer = $('#project_grid .project_slide_container.active');
	var activeProjectSlides = activeProjectSlidesContainer.find('.project_slide');
	
	var projectFilterLi = $('#nav_filters li.filter li');
	var projectFilterLink = $('#nav_filters li.filter a');
	
	var resetFilterLi = $('#nav_filters li#reset_filter');
	var resetFilterLink = $('#nav_filters li#reset_filter a');
	
	var projectGridPagination = $('.pagination_project_grid');
	
	var projectSlidesContainerHeight = 0;
	
	// Empty the pagination nav
	projectGridPagination.empty();
	
	activeProjectSlides.each(
		function() {
			if($(this).height() > projectSlidesContainerHeight) {
				projectSlidesContainerHeight = $(this).height();
			}
			
			var slideIndex = $(this).index() + 1;
			var paginActive;
			
			// Set active classes if it's the first item
			if($(this).index() === 0) {
				$(this).addClass('active');
				paginActive = 'active';
			} else {
				paginActive = '';
			}
			if(activeProjectSlides.length >= 2) {
				// Append a list item for each slide container
				projectGridPagination.append('<li class="' + paginActive + '">' + slideIndex + '</li>');
			}
		}
	);
	
	var projectGridPaginationItem = $('.pagination_project_grid li');
	
	activeProjectSlidesContainer.width(activeProjectSlides.length * 940);
	
	projectGrid.height(projectSlidesContainerHeight);
	
	// Project Nav (dropdown) interaction
	function filterClick(filterItem) {
		projectFilterLi.removeClass('selected');
		filterItem.parent('li').addClass('selected');

		var targetProjectGrid = filterItem.attr('href') + ' #project_grid .project_slide_container > *';
		
		var activeProjectSlidesContainer = $('#project_grid .project_slide_container.active');
		var inactiveProjectSlidesContainer = $('#project_grid .project_slide_container').not('.active');
		
		inactiveProjectSlidesContainer.load(targetProjectGrid, function() {
			var inactiveProjectSlidesContainer = $('#project_grid .project_slide_container').not('.active');
			var inactiveProjectSlides = inactiveProjectSlidesContainer.find('.project_slide');
			var projectSlidesContainerHeight = 0;
			
			
			// Empty the pagination nav
			projectGridPagination.empty();
			
			inactiveProjectSlides.each(
				function() {
					if($(this).height() > projectSlidesContainerHeight) {
						projectSlidesContainerHeight = $(this).height();
					}
				
					var slideIndex = $(this).index() + 1;
					var paginActive;
					
					// Set active classes if it's the first item
					if($(this).index() === 0) {
						$(this).addClass('active');
						paginActive = 'active';
					} else {
						paginActive = '';
					}
					if(inactiveProjectSlides.length >= 2) {
						// Append a list item for each slide container
						projectGridPagination.append('<li class="' + paginActive + '">' + slideIndex + '</li>');
					}
				}
			);
			
			projectGridPaginationItem = $('.pagination_project_grid li');
			
			// Set height of inactive slide container (off-stage)
			inactiveProjectSlidesContainer.width(inactiveProjectSlides.length * 940).height(projectSlidesContainerHeight);
			
			projectGrid.animate({
				height: projectSlidesContainerHeight
			}, 400, 'easeOutQuint', function() {
				activeProjectSlidesContainer.animate({
					left: '-=940px'
				}, 400, 'easeOutQuint', function(){
					$(this)
						.removeClass('active')
						.css('left','940px')
						.empty();
				});
				inactiveProjectSlidesContainer.animate({
					left: '0px'
				}, 400, 'easeOutQuint', function(){
					$(this).addClass('active');
				});
			});
			
			
			gridInteraction();
		});
		
		filterItem.closest('li.active').removeClass('active');
		return false;
	};
	
	
	// Project Filter click
	projectFilterLink.click(function() {
		resetFilterLi.addClass('filter');
		gridTitle.html('Showing all projects for <em>' + $(this).html() + '</em>');
		filterClick($(this));
		return false;
	});
	
	// Reset Filter click
	resetFilterLink.click(function() {
		if(resetFilterLi.hasClass('filter')) {
			location.reload(true);
		} 
		return false;
		
	});
	
	
	// Prevent right-click contect menu for filter menus (dirty, but better than users opening tags' non-existent pages in a new tab/window)
	projectFilterLink.bind('contextmenu',function(e){
		return false;
	});
	
	
	// Pagination interaction
	projectGridPaginationItem.live('click', function() {
		if(!$(this).hasClass('active')){
			var paginationIndex = $(this).index();
			
			projectGridPaginationItem.each(function() {
				if($(this).index() == paginationIndex) {
					
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				}
			});
			
			
			var paginationPixels = '-' + paginationIndex * 940;
			
			activeProjectSlides.eq(paginationIndex).addClass('active');
			
			activeProjectSlidesContainer.animate({
				left: paginationPixels
			}, 400, 'easeOutQuint', function() {
				activeProjectSlides.not(':eq(' + paginationIndex + ')').removeClass('active');
			});
		}		
	});
	
	// Project grid hover interaction
	function gridInteraction() {
		var gridBlock = $('#project_grid .item');
	
		gridBlock.hover(
			function () {
			    $(this).find('div').stop().animate({
					height:"140px"
				}, 400,'easeInQuad');
			},
			function () {
			    $(this).find('div').stop().animate({
					height: "50px"
				}, 600,'easeInQuad');		

			}
		);
		
		gridBlock.click(function() {
			var blockUrl = $(this).find('a').attr('href');
			window.location = blockUrl;
		});
	}
	gridInteraction();
	
}






/*****************************Project Grid************************/
function caseGridInteraction() {
	var projectGrid = $('#case_grid');
	var activeProjectSlidesContainer = $('#case_grid .project_slide_container.active');
	var activeProjectSlides = activeProjectSlidesContainer.find('.project_slide');
	
	var projectGridPagination = $('.pagination_case_grid');
	
	var projectSlidesContainerHeight = 0;
	
	// Empty the pagination nav
	projectGridPagination.empty();
	
	activeProjectSlides.each(
		function() {
			if($(this).height() > projectSlidesContainerHeight) {
				projectSlidesContainerHeight = $(this).height();
			}
			
			var slideIndex = $(this).index() + 1;
			var paginActive;
			
			// Set active classes if it's the first item
			if($(this).index() === 0) {
				$(this).addClass('active');
				paginActive = 'active';
			} else {
				paginActive = '';
			}
			if(activeProjectSlides.length >= 2) {
				// Append a list item for each slide container
				projectGridPagination.append('<li class="' + paginActive + '">' + slideIndex + '</li>');
			}
		}
	);
	
	var projectGridPaginationItem = $('.pagination_case_grid li');
	
	activeProjectSlidesContainer.width(activeProjectSlides.length * 940);
	
	projectGrid.height(projectSlidesContainerHeight);
	

	
	// Pagination interaction
	projectGridPaginationItem.live('click', function() {
		if(!$(this).hasClass('active')){
			var paginationIndex = $(this).index();
			
			projectGridPaginationItem.each(function() {
				if($(this).index() == paginationIndex) {
					
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				}
			});
			
			
			var paginationPixels = '-' + paginationIndex * 940;
			
			activeProjectSlides.eq(paginationIndex).addClass('active');
			
			activeProjectSlidesContainer.animate({
				left: paginationPixels
			}, 400, 'easeOutQuint', function() {
				activeProjectSlides.not(':eq(' + paginationIndex + ')').removeClass('active');
			});
		}		
	});
	
	// Project grid hover interaction
	function gridInteraction() {
		var gridBlock = $('#case_grid .item');
	
		gridBlock.hover(
			function () {
			    $(this).find('div').stop().animate({
					height:"140px"
				}, 400,'easeInQuad');
			},
			function () {
			    $(this).find('div').stop().animate({
					height: "50px"
				}, 600,'easeInQuad');		

			}
		);
		
		gridBlock.click(function() {
			var blockUrl = $(this).find('a').attr('href');
			window.location = blockUrl;
		});
	}
	gridInteraction();
	
}










/*****************************Clear Inputs on focus************************/

function clearText() {
	$('input.clear_text').focus(function() {
		var inputId = $(this).attr('id');
		var defaultValue = $('label[for="'+inputId+'"]').html();

		if($(this).val() == defaultValue) {
			$(this).val('');
		}
	});
	
	$('input.clear_text').blur(function() {
		var inputId = $(this).attr('id');
		var defaultValue = $('label[for="'+inputId+'"]').html();
		
		if($(this).val() === '') {
			$(this).val(defaultValue);
		}
	});
	
}


/*****************************Contact Map************************/
function contactMap() {
	
	// Custom styles JSON for map
	var customStyles=[{featureType:"landscape",elementType:"all",stylers:[{saturation:-99},{lightness:43},{visibility:"simplified"},{hue:"#11ff00"}]},{featureType:"poi.park",elementType:"all",stylers:[{visibility:"simplified"},{hue:"#a4d5a2"}]},{featureType:"poi.medical",elementType:"all",stylers:[{hue:"#ff0011"},{visibility:"simplified"},{saturation:-100},{lightness:12}]},{featureType:"water",elementType:"all",stylers:[{visibility:"simplified"},{hue:"#87b8c1"}]},{featureType:"poi.business",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"road",elementType:"all",stylers:[{visibility:"on"},{saturation:-100},{lightness:12}]},{featureType:"transit.station",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"poi.place_of_worship",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"poi.school",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"poi.attraction",elementType:"all",stylers:[{visibility:"off"}]}];

	function initialize() {
	    var myLatlng = new google.maps.LatLng(51.5126,-0.124052);
	    var myOptions = {
			zoom: 17,
			minZoom: 10,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDefaultUI: true
		};
	    var map = new google.maps.Map(document.getElementById("map"), myOptions);

		var styledMapOptions = {
		    name: "Contact map"
		};
		
		// Custom zoom controls because there's no way to pixel-position controls in V3 API
		function HomeControl(controlDiv, map) {

		    controlDiv.style.marginTop = '10px';
		    controlDiv.style.marginLeft = '10px';

		    // Set CSS for the control border
		    var zoomContainer = document.createElement('div');
		    zoomContainer.style.width = '50px';
		    controlDiv.appendChild(zoomContainer);
		
		
			// Create zoom out div
		    var zoomIn = document.createElement('div');
		    zoomIn.id = 'map_zoom_in';
			zoomIn.innerHTML = "+";
		    zoomContainer.appendChild(zoomIn);
		
			// Create zoom out div
		    var zoomOut = document.createElement('div');
		    zoomOut.id = 'map_zoom_out';
			zoomOut.innerHTML = "-";
		    zoomContainer.appendChild(zoomOut);
			
			// Event listeners for zoom in/out
		    google.maps.event.addDomListener(zoomOut, 'click',
		    function() {
		        map.setZoom(map.getZoom() - 1);
		    });
		
			// Event listeners for zoom in/out
		    google.maps.event.addDomListener(zoomIn, 'click',
		    function() {
		        map.setZoom(map.getZoom() + 1);
		    });
		
			
		}
		
		// Add custom zoom controls
		var homeControlDiv = document.createElement('DIV');
		var homeControl = new HomeControl(homeControlDiv, map);

		homeControlDiv.index = 1;
		map.controls[google.maps.ControlPosition.TOP_LEFT].push(homeControlDiv);

		// Apply custom styles
		var customized = new google.maps.StyledMapType(
		customStyles, styledMapOptions);

		map.mapTypes.set('bostockcustom', customized);
		map.setMapTypeId('bostockcustom');

    
	    var image = new google.maps.MarkerImage("http://dev2011.bostockandpollittdev.com/wp-content/themes/BostockAndPollitt/images/bostock_marker.png",
		new google.maps.Size(136, 20),
		new google.maps.Point(0,0),
		// Anchor (offset) for marker
		new google.maps.Point(0, 10));

	    var marker = new google.maps.Marker({
	        position: myLatlng, 
	        map: map,
			icon: image
	    });
	}

	initialize();
}

/***************************** Validate Email add ************************/
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

/***************************** Email PDF ************************/
function emailPDF() {  
	var pdfLink = $('#emailpdf');
	var pdfFormContainer = $('#page_actions .form_container');
	var pdfForm = pdfFormContainer.find('form');
	var confirmation = pdfFormContainer.find('.confirmation');
	var error = pdfFormContainer.find('.error');
	var textInput = pdfFormContainer.find('#pdfemailaddress');
	var textInputLabelHtml = pdfFormContainer.find('label[for=pdfemailaddress]').html();
	
	pdfLink.click(function() {
		if($(this).parent('li').hasClass('active')) {
			$(this).parent('li').removeClass('active');
			pdfFormContainer.fadeOut('slow');
		} else {
			$(this).parent('li').addClass('active');
			pdfFormContainer.fadeIn('slow');
		}
		return false;
	});
	    
	
	pdfForm.submit(function(){
		var emailAddress = $('#pdfemailaddress').val();
		
		// Function to handle showing success message	
		function pdfSuccess() {
		    pdfForm.animate({
		        left: '-220px'
		    },
		    200, 'easeOutExpo',
				function() {
			        confirmation.css('display', 'block').animate({
			            left: '10'
			        },
			        200, 'easeOutExpo', 
						function() {
							function hideSuccess() {
								pdfLink.parent('li').removeClass('active');
								pdfFormContainer.fadeOut('slow', function() {
									pdfForm.css('left','0');
									confirmation.css({'left': '220px', 'display': 'none'});
									textInput.val(textInputLabelHtml);
									pdfLink.removeClass('active');
								});
							}
							
							setTimeout(hideSuccess, 1500);
						}
					);
				}
			);
		}
		
		
		// Function to handle showing error message
		function pdfError() {

			pdfForm.animate({
			    left: '-220px'
			},
			400, 'easeOutExpo');

			error.css('display', 'block').animate({
			    left: '10'
			},
			400, 'easeOutExpo',
			function() {

			    function hideError() {
			        error.animate({
			            left: '220px'
			        },
			        400, 'easeOutExpo',
			        function() {
			            $(this).css('display', 'none');
			        });

			        pdfForm.animate({
			            left: 0
			        },
			        400, 'easeOutExpo');
			    }
			
				setTimeout(hideError, 1500);

			});
		}
		
		
		if (!isValidEmailAddress(emailAddress)) {
			pdfError();
			return false;
		}
		
		$.ajax({
			type: "POST",
			url: "/wp-content/themes/BostockAndPollitt/email-pdf.php",
			data: "fn="+$('#emailpdf').attr('href')+"&email="+emailAddress,
			success: function(msg){
				pdfSuccess();
			}
		});
		return false;
	});
}


/***************************** Newsletter Signup ************************/
function signup() {
	var signupForms = $('#form_footletter,#form_newsletter');
	
	var confirmation = $('.confirmation');
	var confirmationHeight = confirmation.height();
		
	var formContainer = $('.form_container');
	
	signupForms.each(function() {
		var formContainer = $(this).parent('.form_container');
		formContainer.css('height',$(this).height());
	});
	
	
    signupForms.submit(function(e) {
        e.preventDefault();
        // Grab form action
        var formAction = this.action;
		
		var thisForm = $(this);
		
		var emailAddress = $(this).find('input[name=cm-trjrld-trjrld]').val();

        var thisFormContainer = $(this).parent('.form_container');

		var error = thisFormContainer.find('.error');
		var errorHeight = error.height();

        // Serialize form values to be submitted with POST
        var str = $(this).serialize();
		

		// Function to handle showing success message	
		function signupSuccess() {
		    signupForms.animate({
		        left: '-230px'
		    },
		    200, 'easeOutExpo',
		    function() {
		        formContainer.animate({
		            height: confirmationHeight
		        },
		        200, 'easeOutExpo');

		        confirmation.css('display', 'block').animate({
		            left: '0'
		        },
		        200, 'easeOutExpo');
		    });
		}
		
		
		// Function to handle showing error message
		function signupError() {
			var oldHeight = thisForm.height();

			thisForm.animate({
			    left: '-230px'
			},
			400, 'easeOutExpo');

			thisFormContainer.animate({
			    height: errorHeight
			},
			400, 'easeOutExpo');

			error.css('display', 'block').animate({
			    left: '0'
			},
			400, 'easeOutExpo',
			function() {

			    function hideError() {
			        error.animate({
			            left: '230px'
			        },
			        400, 'easeOutExpo',
			        function() {
			            $(this).css('display', 'none');
			        });

			        thisFormContainer.animate({
			            height: oldHeight
			        },
			        400, 'easeOutExpo');

			        thisForm.animate({
			            left: 0
			        },
			        400, 'easeOutExpo');
			    }
			
				setTimeout(hideError, 1500);

			});
		}
		
		if (!isValidEmailAddress(emailAddress)) {
			signupError();
			return false;
		}
		
        // Add form action to end of serialized data
        var serialized = str + "&action=" + formAction;
        // Submit the form via ajax
        $.ajax({
            url: "/js/proxy.php",
            type: "POST",
            data: serialized,
            dataType: 'html',
            success: function(data) {
                // Server-side validation
                if (data.search(/invalid/i) != -1) {
					signupError();
                }
                else
                {
                    signupSuccess();
                }
            }
        });
    });

}

/* Document Ready Calls */
$(document).ready(function(){
	hashScroll();
	printAction();
	externalLinks();
	clearText();
	siteSearch();
	lastClass();
	jumpLinks();
	signup();
});
