﻿// handle firebug console issues
var sitedebug = true;
if (typeof console == "undefined") { var console = { log: function() {} }; } 
else if (!sitedebug || typeof console.log == "undefined") console.log = function() {};

(function($j) {

	Code.registerNamespace('Website');

	Website.Core = {

		settings: {
			elements: {
				loading: '<div class="loader"></div>',
				hr: '<div class="hr"></div>'
			},
			queryPaths: {
				// search paths
				sitewideSearchToggler: "#searchToggle",
				sitewideSearch: "#sitewideSearch",
				sitewideSearchAction: ".js-search-submit",
				sitewideSearchInput: ".js-search-input",
				// carousel paths
				carouselClass: ".js-carousel",
				// accordion paths
				accordionClass: ".js-accordion",
				accordionItem: ".js-accordion-item",
				accordionToggler: ".js-accordion-toggler",
				accordionItemContent: ".js-accordion-item-content",
				// tweet component
				tweetComponent: ".auto-tweet",
				tweetToggler: ".tweet-toggler",
				tweetContent: ".tweet-content",
				tweetData: ".tweetData"
			},
			classNames: {
				// carousel classes
				carouselAutoPlay: "js-carousel-autoplay",
				carouselLoop: "js-carousel-loop",
				carouselPaginate: "js-carousel-paginate",
				carouselShowPos: "js-carousel-show-pos",
				//accordion classes
				accordionAcceptsTarget: "js-accordion-accepts-target",
				accordionOpenFirstItem: "js-accordion-show-first",
				accordionItemOpenClass: "js-accordion-item-open",
				accordionOneItemVisible: "js-accordion-one-item-opens",
				accordionSpeedSlow: "speed-slow",
				accordionScrollToItem: "scroll-to-item",
				// tweet component
				tweetActive: "tweet-active",
				tweetTogglerActive: "tweet-toggler-active"
			},
			accordionSpeed: "fast",
			autoTweet: false,
			tweetAnimationInterval: 8000 // miliseconds
		},

		// HeaderSearch
		sitewideSearch: function() {
			var self = this;
			var sitewideSearch = $j(self.settings.queryPaths.sitewideSearch);

			// if exists do:
			if (sitewideSearch.size()) {
				// toggle between two functions on click of the searchToggler icon
				$j(self.settings.queryPaths.sitewideSearchToggler).toggle(function(e) {

					// show the search
					sitewideSearch.show();

					// remove focus from toggler
					$j(this).blur();
					
					// focus cursor within the input
					$j(self.settings.queryPaths.sitewideSearchInput).focus();

					$j(self.settings.queryPaths.sitewideSearchInput).keypress(function(e) {
						if (e.keyCode == 13) {
							$j(self.settings.queryPaths.sitewideSearchAction).focus();
							$j(self.settings.queryPaths.sitewideSearchAction).click();
							return false;
						}
					});

				}, function() {
					sitewideSearch.hide();
					$j(this).blur();
				})

			}
		},

		/* scroll to target ID */
		goToByScroll: function(id) {
			$j('html,body').animate({ scrollTop: $j("#" + id).offset().top }, 'slow');
		},

		prettyHr: function() {
			var self = this;
			$j("hr").replaceWith(self.settings.elements.hr);
		},

		// grabs the anchor (to be used as an Id) from the document.location
		getIDfromURLAnchor: function() {
			var self = this;
			var theId = unescape(document.location.hash.substring(1));
			return theId;
		},

		// here we're using the GoogleWebFontAPI to bring a custom web-font and make it load in the same cross-browser
		initWebFonts: function() {
			var self = this;

			WebFont.load({
				custom: { families: ['GrueberBold', 'GrueberRegular'], urls: [Code.resolveUrl('~/_Client/Styles/WebFonts/webfonts.css')] }
			});

			//console.log(Code.resolveUrl('~/_Client/Styles/WebFonts/webfonts.css'));
		},

		// tweet component behaviour

		initTweetComponent: function() {
			var self = this;

			var tweetComponent = $j(self.settings.queryPaths.tweetComponent);

			// if component is on the page
			if (tweetComponent.size()) {

				// do we want the tweet to auto animated open after a set interval? (no typically)
				var autoTweet = self.settings.autoTweet;

				// bind click event to the toggler
				$j(self.settings.queryPaths.tweetToggler, tweetComponent).toggle(function(e) {

					// find toggler and add active class
					var tweetToggler = $j(this);
					tweetToggler.addClass(self.settings.classNames.tweetTogglerActive);

					// ensure width is 0 and animated it over time then show its contents
					$j(self.settings.queryPaths.tweetContent, tweetComponent).css("width", "0px").stop().animate({
						width: '+=380'
					}, 300, function() {
						$j(self.settings.queryPaths.tweetData, this).show();
					});

					// if we're not running an auto-tweet then set a timer to retracted the tweet after the set interval
					if (autoTweet == false) {
						self.tweetTimeOut = window.setTimeout(function() {
							$j(self.settings.queryPaths.tweetToggler, tweetComponent).trigger("click");
						}, self.settings.tweetAnimationInterval);
					}

					// on second click to the reverse of above
				}, function(e) {
					var tweetToggler = $j(this);
					$j(self.settings.queryPaths.tweetData, tweetComponent).hide();
					$j(self.settings.queryPaths.tweetContent, tweetComponent).stop().animate({
						width: '-=450'
					}, 250, function() {
						tweetToggler.removeClass(self.settings.classNames.tweetTogglerActive);
						$j(this).hide();
					});

					// if the toggler is clicked again then cancel the timeout
					if (autoTweet == false) {
						if (typeof self.tweetTimeOut == "number") {
							window.clearTimeout(self.tweetTimeOut);
							delete self.tweetTimeOut;
						}
					}

				});

				if (autoTweet == true) {
					// ever 12 seconds trigger a click on the tweet toggler to run the above code showing/hiding the tweet.
					window.setInterval(function() {
						$j(self.settings.queryPaths.tweetToggler, tweetComponent).trigger("click");
					}, self.settings.tweetAnimationInterval);
				}


			}

		},



		// carousels function (relies on jquery.carousels plugin)
		initCarousels: function() {
			var self = this;

			// don't init carousel if user is in IE7 and zoomed. Frickin thing breaks layout.
			if (Code.UserAgent.isIE7) {
				var rect = document.body.getBoundingClientRect();
				var zoomVal = (Math.round((rect.right - rect.left) / document.body.clientWidth * 100));
				if (zoomVal != 100) {
					return;
				}
			}

			// jQuery object of all found carousels in the document
			var documentCarousels = $j(self.settings.queryPaths.carouselClass);

			// if there are any carousels
			if ($j(documentCarousels).size()) {

				// for each carousel do:
				$j(documentCarousels).each(function() {

					var currentCarousel = this;

					// instantiate configObject
					var configObject = {};

					// test for presence of classes (true or false)
					var autoPlay = $j(currentCarousel).hasClass(self.settings.classNames.carouselAutoPlay);
					var loop = $j(currentCarousel).hasClass(self.settings.classNames.carouselLoop);
					var pagination = $j(currentCarousel).hasClass(self.settings.classNames.carouselPaginate);
					var showCurrentPos = $j(currentCarousel).hasClass(self.settings.classNames.carouselShowPos);

					// if true then update the carousel configuration object accordingly son!
					if (autoPlay == true) {
						configObject.autoSlide = true;
						configObject.autoSlideInterval = 5000;
						configObject.delayAutoSlide = 0;
					}

					// same here, if true then 
					if (loop == true) {
						configObject.loop = true;
					}

					// same here, if true 
					if (pagination == true) {
						configObject.pagination = true;
					}

					if (showCurrentPos == true) {
						configObject.showCurrentPos = true;
					}

					// finally attach carousel behaviour from plugin with our defined configuration object
					$j(currentCarousel).carousel(configObject);

				});

			}

		},

		initAccordions: function() {
			var self = this;

			// jQuery object of all accordions in the document
			var documentAccordions = $j(self.settings.queryPaths.accordionClass);

			// if we found any
			if ($j(documentAccordions).size()) {

				// loop through each accordion and do the following:
				documentAccordions.each(function() {

					// ref the current accordion we're working with
					var currentAccordion = $j(this);

					// some configuration variables
					var theTargetItem = self.getIDfromURLAnchor();

					// the following check for the existing of a class on the accordion, they return true or false this way we can configure each individual accordion
					var acceptsTargetItem = currentAccordion.hasClass(self.settings.classNames.accordionAcceptsTarget);
					var openFirstItem = currentAccordion.hasClass(self.settings.classNames.accordionOpenFirstItem);
					var oneItemVisible = currentAccordion.hasClass(self.settings.classNames.accordionOneItemVisible);
					var speedSlowSet = currentAccordion.hasClass(self.settings.classNames.accordionSpeedSlow);
					var scrollToItem = currentAccordion.hasClass(self.settings.classNames.accordionScrollToItem);
					var accordionSpeed = "fast";

					if (speedSlowSet == true) {
						accordionSpeed = "slow";
					}

					// if parameter classes are added correctly and with have an achor in the URL open that item's content div
					if (acceptsTargetItem == true && theTargetItem !== "" && openFirstItem == false) {

						$j("#" + theTargetItem).addClass(self.settings.classNames.accordionItemOpenClass);
						$j(self.settings.queryPaths.accordionItemContent, "#" + theTargetItem).show();

						// if above test fails but this is true then show the first item's content div
					} else if (openFirstItem == true) {
						currentAccordion.find(self.settings.queryPaths.accordionItem + ":first " + self.settings.queryPaths.accordionItemContent).addClass(self.settings.classNames.accordionItemOpenClass).show();
					}

					// attach the click event to the accordion toggler link (we know its a link because for non-js we want to it to jump to an anchor)
					$j(self.settings.queryPaths.accordionToggler + " a", currentAccordion).click(function(e) {

						// grabbing the current accordion's Id from toggler link's href with *should* be the Id for accordionItem
						var clickedAccordionItemId = $j(this).attr("href");
						clickedAccordionItemId = clickedAccordionItemId.substr(1);

						var clickedAccordionItem = $j(this).closest(self.settings.queryPaths.accordionItem);

						// grab the item's content element we want to show/hide
						var itemContentToToggle = clickedAccordionItem.find(self.settings.queryPaths.accordionItemContent);

						// find all the sibling accordion Items (using parentUntil because not necessarily all within the same container)
						var siblingItems = itemContentToToggle.parentsUntil(currentAccordion).siblings().find(self.settings.queryPaths.accordionItemContent).parent();

						// toggle open class on the item we clicked
						clickedAccordionItem.toggleClass(self.settings.classNames.accordionItemOpenClass);

						// if we only want one item visible at a time then
						if (oneItemVisible == true) {

							// slideToggle the current item then scroll to that anchor whilst at the same time finding all the others and have them slide up
							itemContentToToggle.slideToggle(accordionSpeed, function() {
								if (scrollToItem == true) {
									self.goToByScroll(clickedAccordionItemId);
								}
							}).parentsUntil(currentAccordion).siblings().find(self.settings.queryPaths.accordionItemContent).slideUp("fast");

							// remove the open class should it be present on any of the other accordionItems
							siblingItems.removeClass(self.settings.classNames.accordionItemOpenClass);


							// if we're happy for them to stay open together then we'll just slideToggle our target accordion item's content div.
						} else {
							// toggle the open class on the accordion item element
							itemContentToToggle.slideToggle(accordionSpeed);
						}

						// remove focus
						$j(this).blur();

						// remove default browser events
						e.preventDefault();

					});

				});

			}

		},
		
		initExternalLinks: function() {
			
			var self = this;
			$j("a[href^=http]").each(function(){
				if(this.href.indexOf(location.hostname) == -1) {
					$(this).attr('target', '_blank');
				}			
			});
		
		},
		
		/* front-end tool for checking design integrity - relies on plugin in /lib/ */
		gridTool: function(opacity) {
			$j("body").addGrid(16, { img_path: '/_Client/Images/Global/', opacity: opacity });
		},

		/*
		* function onReady 
		*/
		onReady: function() {
			var self = this;
			self.prettyHr();
			self.sitewideSearch();
			self.initWebFonts();
			self.initCarousels();
			self.initAccordions();
			self.getIDfromURLAnchor();
			self.initTweetComponent();
			self.initExternalLinks();
			// self.gridTool();

		}

	};

	$j().ready(function() {
		Website.Core.onReady();
	});

})(jQuery);	


