$(function () {

	// Initialise Google Tracking for File Downloads
	googleAnalyticsFileTracker();
	Equalise($(".content-body .content-left, .content-body .content-right"));
	PolyFills.All();
	if ($('.gallery #image-gallery').size() > 0) {
		Gallery.Main.run();
	}
	if ($('.about-us .housing').size() > 0) {
		Equalise($(".about-us .housing"));
	}
});

function Equalise(elms){
	// usage:
	// Equalise($(".list li"));
	// Equalise($("#nav, #content"));
	var highest = 0;
	for(i=0; i < elms.length; i++){ if($(elms[i]).height() > highest) highest = $(elms[i]).height(); }
	for(i=0; i < elms.length; i++){ if($(elms[i]).height() < highest) $(elms[i]).height(highest); }
}


// Google Analytics File Download Tracking
function googleAnalyticsFileTracker() {
	$("a[href$=.pdf],a[href$=.doc],a[href$=.docx],a[href$=.xls],a[href$=.xlsx],a[href$=.ppt],a[href$=.pptx]").click(function() {
		pageTracker._trackPageview($(this).attr("href"));
	});
}

var PolyFills = {
	Page: (function () {
		function run() {
			if (document.getElementsByTagName('html')[0].className.indexOf('no-borderradius') !== -1) {
				$('<div id="content-wrapper"></div>').insertBefore("#content.home, #content.gallery, #content.sitemap, #content.rangelist");
				$('<div id="content-wrapper" class="no-left-margin"></div>').insertBefore("#content.range .product-details, #content.standard .heading, #content.standard .content-body");
				$('<div id="content-wrapper" class="where"></div>').insertBefore("#content.where");
				$('<div class="nav-wrapper"></div>').insertBefore(".nav, .logo");
			}
		}
		return {
			run: run
		}
	})(),
	All : function(){
		PolyFills.Page.run();
	}
}

var Gallery = {

	//Main Function to run the Gallery
	Main: (function () {

		function run() {
			Gallery.Rotator.init();
		}

		return {
			run: run
		}
	})(),

	//Maintains the state of the gallery i.e. is it transitioning
	State: (function () {

		var galleryTransitionActive = false;

		return {
			galleryTransitionActive: galleryTransitionActive
		}

	})(),

	//Functionality for the Rotator
	Rotator: (function () {

		var $selected,
			$menu,
			$menuItems,
			imageGalleryClass,
			$listing;

		//Initial setup of rotator and important variables
		function init() {
			SetControllerEvents();
			SetMenuEvents();
			$selected = $('#image-gallery').find('.image-listing')
							.find('.selected');
			$listing = $('#image-gallery').find('.listing');
		}

		//Set events for next and previous controls
		function SetControllerEvents() {
			$.each([$('#next'), $('#previous')], function (index, value) {
				value.click(function (event) {
					if (!Gallery.State.galleryTransitionActive && !$(this).is(".disabled")) {
						event.preventDefault();
						Gallery.State.galleryTransitionActive = true;
						var direction = this.id,
							$nextMenuItem = direction === 'next' ? $menu.find('.selected').next() : $menu.find('.selected').prev();
						imageGalleryClass = $nextMenuItem.attr("class").replace(/\s*?(selected)?\s*?/, "");
						PrepareForSlide(direction);
						Slide(direction);
						CleanUpMenu();
					}
				});
			})
		}

		//Set events for menu navigation
		function SetMenuEvents() {
			$menu = $('#image-gallery').find('.menu');
			$menuItems = $menu.find('li');
			$menuItems.each(function () {
				$(this).click(function (event) {
					event.preventDefault();
					var $thisLi = $(this);
					// console.log(Gallery.State.galleryTransitionActive);
					if (!Gallery.State.galleryTransitionActive && !$thisLi.is(".selected")) {
						Gallery.State.galleryTransitionActive = true;
						imageGalleryClass = $thisLi.attr("class").replace(/\s*?(selected)?\s*?/, "");
						direction = $selected.nextAll('.' + imageGalleryClass).length > 0 ? "next" : "previous";
						PrepareForSlide(direction, imageGalleryClass);
						Slide(direction, imageGalleryClass);
						CleanUpMenu();
					}
				});
			});
		}

		//Once a new item has been selected in the menu this method "cleans up" the selected class and the mask
		function CleanUpMenu() {
			$menu.find('.selected')
				.removeClass('selected')
				.find('#mask')
					.empty()
					.remove();
			$menu.find('.' + imageGalleryClass)
				.removeClass("next-selected")
				.addClass("selected")
				.append('<div id="mask">&nbsp;</div>');
		}

		//Just before we slide to the next selected item, we do some preprocessing depending whether we are going previous or next
		function PrepareForSlide(direction, id) {
			if (direction === "next") {
				if (id !== undefined) {
					$selected.parent().find('.' + id).addClass("moving-to-next");
				} else {
					$selected.next().addClass("moving-to-next");
				}

			} else {
				if (id !== undefined) {
					$selected.parent().find('.' + id).addClass("moving-to-previous");
				} else {
					$selected.prev().addClass("moving-to-previous");
				}
			}
		}

		//The animated slide
		function Slide(direction, classToFind) {

			var $itemToMove = direction === "next"
						? $selected : classToFind !== undefined
							? $selected.parent().find('.' + classToFind) : $selected.prev(),
				positionToMoveTo = direction === "next"
					? "650px" : "0";

			ShowContent();

			$itemToMove.animate({
				left: positionToMoveTo
			}, 1000, "easeOutQuint", function () {
				CleanUpPostSlide();
				ClearStyles('.image-listing li');
			});
		}

		//Reset all the jQuery css styles so the css styles aren't overwritten
		function ClearStyles(elem) {
			$(elem).each(function () { $(this).removeAttr("style"); })
		}

		//Clean up the listing/image rotator after the slide i.e. set selected etc 
		function CleanUpPostSlide() {
			CleanUpMenu();
			$selected.removeClass("selected");
			$(".image-listing .moving-to-next, .image-listing .moving-to-previous").each(function () {
				$(this).addClass("selected")
					.removeClass("moving-to-next moving-to-previous");
			});
			$selected = $('#image-gallery').find('.image-listing')
							.find('.selected');
			SetButtons();
			Gallery.State.galleryTransitionActive = false;
		}

		//Determine whether the next and previous buttons should be enabled/disabled after a transition
		function SetButtons() {
			$.each([$('#next'), $('#previous')], function () {
				var $thisButton = $(this),
					$nextSelected = $thisButton.attr("id") === "next" ? $selected.next() : $selected.prev();
				if ($nextSelected.length === 0) {
					$thisButton.addClass("disabled");
				} else {
					$thisButton.removeClass("disabled");
				}
			});
		}

		//Fade out the current content and fade in the next content that is selected
		function ShowContent() {
			$listing.find('.selected')
				.animate({
					"opacity": "0"
				}, 500, "easeInExpo", function () {
					$(this).css("display", "none")
					$listing.find('.' + imageGalleryClass).css({
						"opacity": 0,
						"display": "block"
					}).animate({
						"opacity": "1"
					}, 500, "easeOutSine", function () {
						if (jQuery.browser.msie) {
							this.style.removeAttribute('filter');
						}
						$(this).parent().find('.selected').removeClass("selected");
						$(this).addClass('selected');
					});
				});
		}

		return {
			init: init
		}

	})()
}

/** This is the Image Rotator used on the homepage **/
		var ImageRotator = (function (params) {
			var $selected,
				imageGalleryClass,
				$listing,
				galleryTransitionActive = false,
				defaults = {
					listing: '#image-gallery',
					next: '#next',
					previous: '#previous'
				},
				config = $.extend(defaults, params);

			//Initial setup of rotator and important variables
			function init() {
				$(this).find('ul').wrapInner("<div id='rotator-window'></div>");
				SetControllerEvents();
				$selected = $(config.listing).find('.selected');
				$listing = $(config.listing).find('ul');
			}

			//Set events for next and previous controls
			function SetControllerEvents() {
				$.each([$(config.next), $(config.previous)], function (index, value) {
					value.click(function (event) {
						if (!galleryTransitionActive && !$(this).is(".disabled")) {
							event.preventDefault();
							galleryTransitionActive = true;
							var direction = this.id,
								$nextItem = direction === 'next' ? $listing.find('.selected').next() : $listing.find('.selected').prev();
							//imageGalleryClass = $nextItem.attr("class").replace(/\s*?(selected)?\s*?/, "");
							PrepareForSlide(direction);
							Slide(direction);
						}
					});
				})
			}

			//Just before we slide to the next selected item, we do some preprocessing depending whether we are going previous or next
			function PrepareForSlide(direction, id) {
				if (direction === "next") {
					if (id !== undefined) {
						$selected.parent().find('.' + id).addClass("moving-to-next");
					} else {
						$selected.next().addClass("moving-to-next");
					}

				} else {
					if (id !== undefined) {
						$selected.parent().find('.' + id).addClass("moving-to-previous");
					} else {
						$selected.prev().addClass("moving-to-previous");
					}
				}
			}

			//The animated slide
			function Slide(direction, classToFind) {

				var $itemToMove = direction === "next"
							? $selected : classToFind !== undefined
								? $selected.parent().find('.' + classToFind) : $selected.prev(),
					positionToMoveTo = direction === "next"
						? "650px" : "0";

				$itemToMove.animate({
					left: positionToMoveTo
				}, 1000, "easeOutQuint", function () {
					CleanUpPostSlide();
					ClearStyles('.image-listing li');
				});
			}

			//Reset all the jQuery css styles so the css styles aren't overwritten
			function ClearStyles(elem) {
				$(elem).each(function () { $(this).removeAttr("style"); })
			}

			//Clean up the listing/image rotator after the slide i.e. set selected etc 
			function CleanUpPostSlide() {
				$selected.removeClass("selected");
				$listing.find(".moving-to-next, .moving-to-previous").each(function () {
					$(this).addClass("selected")
						.removeClass("moving-to-next moving-to-previous");
				});
				$selected = $listing.find('.selected');
				SetButtons();
				galleryTransitionActive = false;
			}

			//Determine whether the next and previous buttons should be enabled/disabled after a transition
			function SetButtons() {
				$.each([$('#next'), $('#previous')], function () {
					var $thisButton = $(this),
						$nextSelected = $thisButton.attr("id") === "next" ? $selected.next() : $selected.prev();
					if ($nextSelected.length === 0) {
						$thisButton.addClass("disabled");
					} else {
						$thisButton.removeClass("disabled");
					}
				});
			}

			return {
				init: init
			}
		})();

