(function(w,d,$){
	"use strict";
	$(":root").addClass('js');
	$(d).ready(function(){
		$(w).load(function(){
			$(":root").addClass('done');
			w.fixAllHeights();
		});
		// Code to set correct tracking account in GA across domains
		setTimeout(function(){
			if (typeof ga === 'function'){
				var clientId;
				ga(function(tracker) {
					clientId = tracker.get('clientId');
				});
				if (clientId !== ''){
					var domain=window.location.host.replace(/www\./,'').replace(/content\./,'').replace(/blog\./,'');
					var prefix=window.location.host.replace(new RegExp(domain,"g"),'');
					$("a[href*='"+domain+"']:not([href*='"+prefix+"'])").each(function(){
						var patt = new RegExp(/\?/);
						$(this).attr('href',$(this).attr('href')+(patt.test($(this).attr('href'))?"&":"?")+'clientId='+clientId);
					});
				}
			}
		},1000);

		// $("a[href^=tel]").click(function(e){
			// if ($(window).width() > 600){
				// e.preventDefault();
				// return false;
			// }
		// });

		// remove borders from link images
		$(".typography a > img").parent('a').addClass('no-border');



		if (typeof iFrameResize === 'function') {
			window._iframes = iFrameResize( {}, "iframe.iframe-resize");
		}

		$("a[href^=http]").not('[href*="'+(window.location.host.replace(/^www\./,''))+'"]').each(function(){
			var lnk=this;
			window._pcbLinkShouldWarn(lnk.href).then(function(result) {
				if (result === true) {
					$(lnk).click(function(e){
						e.preventDefault();
						new ExternalLinkNotice($(lnk).attr('href'));
					});
				}
			});
		});

		// the original script above excludes running the external link notice on hrefs that contain the current domain. but we need the
		//the current domain in the url to create social links.
		$("a.custom-social-link" ).each(function(){
			var lnk=this;
			window._pcbLinkShouldWarn(lnk.href).then(function(result) {
				if (result === true) {
					$(lnk).click(function(e){
						e.preventDefault();
						new ExternalLinkNotice($(lnk).attr('href'));
					});
				}
			});
		});

		w.addResponsiveAdjustment(function(){
			w.fixAllHeights();
			w.fixIframes($(".typography iframe[src*=youtu]"));
		});

		if ($("#login-box").length) {
			$("body").click(function(e){
				if ($("#login-box")[0]._isShown()){
					if ( (!$(e.target).is("#login-drop")) && (!$(e.target).parents("#login-box").length) ){
						$("#login-box")[0]._hide();
					}
				}
			});

			$(".toggle-login").click(function(e){
				e.preventDefault();
				$("#login-box")[0]._toggle();
			});
			$.extend($("#login-box")[0],_loginBox);
			var resizeTimer1,resizeTimer2;
			var size = $(window).width();
			$(window).resize(function() {
				// is a timer already running
				// if (resizeTimer1 === undefined) {
				// 	// starting width
				// 	resizeTimer1 = setInterval(function(){
				// 		if ( ($(window).width() > size + 50) || ($(window).width() < size - 50) ) { // enough change, close the box
				// 			$("#login-box")[0]._hide();
				// 		}
				// 	},300);
				// 	resizeTimer2 = setInterval(function(){
				// 		if (size === $(window).width()) { // size is no longer changing, reset the base size and kill the timer
				// 			size = $(window).width();
				// 			resizeTimer1 = undefined;
				// 			resizeTimer2 = undefined;
				// 		}
				// 	},1000);
				// }
			});
		}
	});

	window._pcbLinkShouldWarn = function(href){
		return new Promise(function(resolve) {
			for(var i=0;i<window._thirdPartyNotice.whitelisted.length;i++) {
				var regex = new RegExp(window._thirdPartyNotice.whitelisted[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&').toLowerCase());
				if (href.search(regex) > -1) {
					resolve(false);
					return;
				}
			}
			setTimeout(function(){
				resolve(true);
			},0);
		});
	};

	var _loginBox = {
		_timer: 0,
		_canToggle: true,
		_bodyClass: 'show-login',
		_isShown: function(){
			return $("body").hasClass(this._bodyClass);
		},
		_show: function(){
			if (this._canToggle) {
				this._canToggle = false;
				$(this).find('*').removeClass('m-current');
				if (!$(this).find('.account-form.current').length) {
					$(this).find('.account-form').filter('[data-form="'+$("#current-login-account-type").val()+'"]').addClass('current');
				}
				$("body").addClass(this._bodyClass);
				var me=this;
				setTimeout(function(){
					me._canToggle = true;
				},500);
			}
			return this;
		},
		_hide: function(){
			if (this._canToggle) {
				this._canToggle = false;
				$("body").removeClass(this._bodyClass);
				var me=this;
				setTimeout(function(){
					me._canToggle = true;
				},500);
			}
			return this;
		},
		_toggle: function(){
			if (this._isShown()) {
				this._hide();
			} else {
				this._show();
			}
			return this;
		}
	};

	var ExternalLinkNotice = function(href, target){
		if (window._thirdPartyNotice === undefined) {
			return;
		}
		target = target || '_blank';
		this.container = $("<div></div>");
		this.container.addClass('notice-modal');
		$("body").append(this.container);

		this.content = $("<div></div>");
		this.content.addClass('notice-modal-content typography');
		this.container.append(this.content);

		if (window._thirdPartyNotice.title !== undefined) {
			this.title = $("<div></div>");
			this.title
				.addClass('notice-modal-title')
				.text(window._thirdPartyNotice.title);
			this.content.append(this.title);
		}
		this.text = $("<div></div>");
		this.text
			.addClass('notice-modal-text')
			.html(window._thirdPartyNotice.content);
		this.content.append(this.text);

		this.a_cont = $("<a></a>");
		this.a_cont.attr('target',target)
			.attr('href',href)
			.addClass('btn btn-blue notice-modal-btn')
			.text('Continue')
			.click(function(){
				$(this).parents('.notice-modal').fadeOut(100,'linear',function(){
					$(this).remove();
				});
			});
		this.content.append(this.a_cont);

		this.a_cancel = $("<a></a>");
		this.a_cancel.attr('href','#')
			.addClass('btn btn-blue notice-modal-btn')
			.text('Cancel')
			.click(function(){
				$(this).parents('.notice-modal').fadeOut(100,'linear',function(){
					$(this).remove();
				});
			});
		this.content.append(this.a_cancel);

		this.close_btn = $("<a></a>");
		this.close_btn.attr('href','#')
			.addClass('notice-modal-close')
			.html('&times')
			.click(function(){
				$(this).parents('.notice-modal').fadeOut(100,'linear',function(){
					$(this).remove();
				});
			});
		this.content.append(this.close_btn);

		this.container.addClass('show');
		return this;
	};

	w.fixIframes = function(iframes){
		iframes.each(function(){
			if (!$(this).attr('ratio') && $(this).attr('height') && $(this).attr('width')){
				$(this).attr('ratio',(parseInt($(this).attr('height'))/parseInt($(this).attr('width'))));
				var src=$(this).attr('src');
				$(this).attr('src',src+((src.indexOf("?") !== -1)?"&":"?")+'wmode=transparent').removeAttr('height');
			}
		});
		setTimeout(function(){
			iframes.each(function(){
				if($(this).attr('ratio')){
					$(this).height($(this).width() * $(this).attr('ratio'));
				}
			});
		},500);
	};

	w.fixAllHeights = function(){
		w.fixHeights({selector:'.parent_sameheight', method:'parent'});
		w.fixHeights({selector:'.sameheight', method:'match'});
		var matchObjectHeights = {};
		$("[data-match-height]").each(function(){
			if (matchObjectHeights[$(this).data('match-height')] === undefined) {
				matchObjectHeights[$(this).data('match-height')] = true;
				w.matchHeights($('[data-match-height="'+$(this).data('match-height')+'"]'));
			}
		});
		var matchHeightSize = "small";
		if ($(window).width() > 800) {
			matchHeightSize = "large";
		} else if ($(window).width() > 500) {
			matchHeightSize = "medium";
		}
		$("[data-match-height-"+matchHeightSize+"]").each(function(){
			if (matchObjectHeights[$(this).data('match-height-'+matchHeightSize)] === undefined) {
				matchObjectHeights[$(this).data('match-height-'+matchHeightSize)] = true;
				w.matchHeights($('[data-match-height-'+matchHeightSize+'="'+$(this).data('match-height-'+matchHeightSize)+'"]'));
			}
		});

	};

	// For info on how to use this function, check the wiki: http://iqwebwork.com/wiki/index.php?title=SilverStripe_Tips_%26_Tricks#Using_fixHeights.28.29_to_make_your_content_and_sidebar_the_same_height
	w.fixHeights = function(params){
		if(params){
			var selector = params.selector;
			var method = params.method;

			switch(method)
			{
				case "parent":
					$(selector).css('min-height','0px');
					$(selector).each(function(){
						$(this).css('min-height',($(this).parent().height())+'px');
					});
					break;
				case "match":
					var max_height = [];
					$(selector).css("height", "auto");
					$(selector).each(function(){
						if (!max_height[$(this).attr("rel")]){ max_height[$(this).attr("rel")] = 0; }
						var my_height = $(this).outerHeight(false);
						if ($(this).attr("lang")) { my_height += parseInt($(this).attr("lang")); }
						max_height[$(this).attr("rel")] = Math.max(max_height[$(this).attr("rel")], my_height);
					});
					$(selector).each(function(){
						$(this).height(max_height[$(this).attr("rel")] - (parseInt($(this).css("padding-top"), 10) + parseInt($(this).css("padding-bottom"), 10) + parseInt($(this).css("border-top-width"), 10) + parseInt($(this).css("border-bottom-width"), 10)));
					});
					break;
			}
		}
	};

	w.matchHeights = function(objects){
		if($(objects).length > 1){
			var max_height=0;
			$(objects).css("height", "auto");
			$(objects).each(function(){
				var my_height = $(this).outerHeight(false);
				max_height = Math.max(max_height, my_height);
			});
			$(objects).each(function(){
				$(this).height(max_height - (parseInt($(this).css("padding-top"), 10) + parseInt($(this).css("padding-bottom"), 10) + parseInt($(this).css("border-top-width"), 10) + parseInt($(this).css("border-bottom-width"), 10)));
			});

		}
	};

	w.jScroll = function(anchor_name){
		var aTag = $("a[name='"+anchor_name+"']");
		$('html,body').animate({scrollTop: aTag.offset().top},'slow');
	};
	// close custom modal
	$(document).on('click', '#close-modal', function() {
		console.log('working');
		jQuery('.custom-newsletter-modal').fadeOut();
	});
}(window,document,jQuery));