if (typeof TwineSDK == 'undefined') {

	Twine = {}; // global object container
	Twine.frameArray = new Array();

	var TwineSDK = {

		// default to autoLoad the hub; set to false to manually load
		autoLoad: true,

		// default settings for networks
		// an example:
		networks: {},

		// load the Twine hub using this specific tab id
		// it sends it to the first twine iframe on the page
		// no way to send it into a second iframe on the page
		// we could send in a parameter if it is a problem
		LoadTabById: function (tabId) {
			document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "load-tab",data: tabId}), "*");
		},
		
		setIFrameSrc: function(nurl,iFrameID) {
			if (!document.getElementById(iFrameID).src) {
				document.getElementById(iFrameID).src = nurl;
			}
		},
		
		executeCTAEvent: function(el) {	
			action = jQuery(el).attr('data-cta-action');
			cta_id = jQuery(el).attr('data-cta-id');
			
			if (action == "show_detail") {
				
				var media_id = jQuery(el).attr("data-media-id");
			
				if (jQuery(el).attr("data-has-detail") !== "true") {
					jQuery(el).addClass('active');
					window.open(jQuery(el).attr("data-target-url"));
					this.logCTAEvent('click_through',jQuery(el).attr("data-cta-id"),media_id);
				} else {			
					if (jQuery(".cta-details-wrapper .cta-detail.active").length > 0) {
						jQuery(".cta-details-wrapper .cta-detail.active").removeClass("active").fadeOut(150);
					}
			
					if (jQuery(".image_size_wrapper .cta_hotspot.active").length > 0) {
						jQuery(".image_size_wrapper .cta_hotspot.active").removeClass("active");
					}							
		
					jQuery(el).addClass('active');
					var index = jQuery(el).index();
		
					//jQuery(".cta-details-wrapper .cta-detail").eq(index-1).fadeIn(150).addClass("active");				
					jQuery(".cta-details-wrapper .cta-detail[data-id=" + cta_id + "]").eq(0).fadeIn(150).addClass("active");
				
					this.logCTAEvent('show_detail',jQuery(el).attr("data-cta-id"),media_id);											
				}
			} else if (action == "click_through") {								
				var media_id = jQuery(el).attr("data-media-id");
												
				window.open(jQuery(el).attr("data-target-url"));
				this.logCTAEvent('click_through',jQuery(el).attr("data-cta-id"),media_id);
			}
		},
		
		// logs details view and hits to target url for CTAs
		logCTAEvent: function(type,cta_id,media_id) {
						
			if (type == "show_detail") {
				document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "cta_log_show_detail",data:{"media_id":media_id,"cta_id":cta_id}}), "*");
				
			} else if (type == "click_through") {
				document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "cta_log_click_through",data:{"media_id":media_id,"cta_id":cta_id}}), "*");
			} else {
				console.log("Unsupported CTA event detected. Aborting.");
			}
		},
		
		HideModals: function() {
			document.getElementById('twine-modal-player').style.display="none";
			document.getElementById('twine-modal-editor').style.display="none";
			document.getElementById('twine-modal-creator').style.display="none";
			document.getElementById('twine-modal-prompt').style.display="none";
			document.getElementById('twine-modal-prompt').innerHTML = "<h2></h2><p></p>";

			if (document.getElementById('twine-video-iframe') !== null) {
				document.getElementById('twine-video-iframe').src="";
			}

			if (document.getElementById('twine-editor-iframe') !== null) {
				document.getElementById('twine-editor-iframe').src="";
			}
			
			if (document.getElementById('twine-creator-iframe') !== null) {
				document.getElementById('twine-creator-iframe').src="";
			}			

			document.getElementById('twine-modal-background').style.display="none";

			jQuery('#twine-modal-background').clearQueue();

		},
		
		// create the DIV elements that we load in our toolbars, backgrounds, and player elements
		CreateTwineElements: function () {

			// create the black background
			var h = document.createElement("div");
			h.id ="twine-modal-background";
			document.body.appendChild(h);

			var i = document.createElement("div");
			i.id ="twine-modal-player";
			i.className="twine-reset";
			document.body.appendChild(i);

			var i = document.createElement("div");
			i.id ="twine-modal-editor";
			i.className="twine-reset";
			document.body.appendChild(i);
			
			var i = document.createElement("div");
			i.id ="twine-modal-creator";
			i.className="twine-reset";			
			document.body.appendChild(i);

			var i = document.createElement("div");
			i.id ="twine-modal-prompt";
			i.className="twine-reset";	
			i.innerHTML = "<div id='twine-close'></div><div id='prompt-inner'></div>";
			
			document.body.appendChild(i);
								
			// create the toolbar
			var h = document.createElement("div");
			h.id ="twine-toolbar";
			h.className="twine-reset";

			document.body.appendChild(h);

		},
		
		InstallToolbarListeners: function() {
			TwineSDK.installListener(document.getElementById('twine-toolbar-launcher'),'click',function() {
				jQuery('#twine-toolbar-launcher').fadeOut();
				jQuery('#twine-toolbar-content-frame').slideDown();
			});
			
			TwineSDK.installListener(document.getElementById('twine-toolbar-launcher'),'dragover',function() {
				jQuery('#twine-toolbar-launcher').fadeOut();
				jQuery('#twine-toolbar-content-frame').slideDown();
			});			
		},
		
		// function to handle clicking of share buttons
		ShareAction: function(element) {
			mat = jQuery(element).attr("data-action");
			tn = jQuery(element).attr("data-target");
			url = jQuery(element).attr("data-url");
			
			if (mat !== "Vote") {											
				document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "log-share-action",data: {id: jQuery(element).attr("data-id"), source: jQuery(element).attr("data-target"), action: jQuery(element).attr("data-action"), link: jQuery(element).attr("data-href")}}), "*");
			}
			
			if (jQuery(element).attr("data-action") == "View") {
				!window.open(jQuery(element).attr("data-href"),"_blank");
				return;
			}

			mat = jQuery(element).attr("data-action");
			tn = jQuery(element).attr("data-target");
			url = jQuery(element).attr("data-url");

			switch (mat) {

			case "Share":

				if (tn=="Facebook") {					
					return !window.open(url,"_blank","menubar=no,height=350,width=600");
				} else if (tn=="LinkedIn") {
					return !window.open(url,"_blank","menubar=no,height=350,width=600");
				} else if (tn=="GooglePlus") {
					return !window.open(url,"_blank","menubar=no,height=600,width=600");
				}
				break;

			case "Pin":
				return !window.open(url,"_blank","menubar=no,height=350,width=600");
				break;

			case "Tweet":						
				return !window.open(url,"_blank","menubar=no,height=350,width=600");				
				break;

			case "Retweet":				
				return !window.open(url,"_blank","menubar=no,height=350,width=600");
				break;

			case "Favorite":
				return !window.open(url,"_blank","menubar=no,height=350,width=600");
				break;
				
			case "Vote":
				document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "post-vote",data: {id: jQuery(element).attr("data-id")}}), "*");
				break;			
			}

		},		

		DestroyToolbar: function() {
			jQuery('#twine-toolbar').empty();
		},
		ShrinkToolbar: function() {
			jQuery('#twine-toolbar-content-frame').removeClass('twine-toolbar-expanded');
		},
		ExpandToolbar: function() {
			jQuery('#twine-toolbar-content-frame').addClass('twine-toolbar-expanded');
		},
		MinimizeToolbar: function() {
			jQuery('#twine-toolbar-launcher').fadeIn();
			jQuery('#twine-toolbar-content-frame').fadeOut();
		},					
		CloseEditor: function() {
			jQuery('#twine-modal-editor').fadeOut();
			jQuery('#twine-modal-background').fadeOut();
		},		
		CloseCreator: function() {
			jQuery('#twine-modal-creator').fadeOut();
			jQuery('#twine-modal-background').fadeOut();
		},	
		ClosePrompt: function() {
			jQuery('#twine-modal-prompt').fadeOut();
			jQuery('#twine-modal-background').fadeOut();
		},	
		SizerHeight: function () {
			return Math.max(Math.max(document.body.scrollHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), Math.max(document.body.clientHeight, document.documentElement.clientHeight))
		},
		getPageOffset: function () {
				return window.pageYOffset ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop || document.body.scrollTop
		},
		getPageHeight: function () {
				return this.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
		},
		Base64: {

			// private property
			_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
			decode: function (input) {
				var output = "";
				var chr1, chr2, chr3;
				var enc1, enc2, enc3, enc4;
				var i = 0;

				input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

				while (i < input.length) {

					enc1 = this._keyStr.indexOf(input.charAt(i++));
					enc2 = this._keyStr.indexOf(input.charAt(i++));
					enc3 = this._keyStr.indexOf(input.charAt(i++));
					enc4 = this._keyStr.indexOf(input.charAt(i++));

					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;

					output = output + String.fromCharCode(chr1);

					if (enc3 != 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 != 64) {
						output = output + String.fromCharCode(chr3);
					}

				}

				output = this._utf8_decode(output);

				return String(output);

			},

			// private method for UTF-8 decoding
			_utf8_decode : function (utftext) {
				var string = "";
				var i = 0;
				var c = c1 = c2 = 0;

				while ( i < utftext.length ) {

					c = utftext.charCodeAt(i);

					if (c < 128) {
						string += String.fromCharCode(c);
						i++;
					}
					else if((c > 191) && (c < 224)) {
						c2 = utftext.charCodeAt(i+1);
						string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
						i += 2;
					}
					else {
						c2 = utftext.charCodeAt(i+1);
						c3 = utftext.charCodeAt(i+2);
						string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
						i += 3;
					}

				}

				return string;
			}
		},

		getViewport: function() {
			var viewPortWidth;
			var viewPortHeight;

			// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			if (typeof window.innerWidth != 'undefined') {
				viewPortWidth = window.innerWidth,
				viewPortHeight = window.innerHeight
			}
			// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
			else if (typeof document.documentElement != 'undefined'
				&& typeof document.documentElement.clientWidth !=
				'undefined' && document.documentElement.clientWidth != 0) {
				viewPortWidth = document.documentElement.clientWidth,
				viewPortHeight = document.documentElement.clientHeight
			}

			// older versions of IE
			else {
				viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
				viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
			}
			return [Math.round(viewPortWidth), Math.round(viewPortHeight)];
		},
		
		passDimensionsToIFrame: function() {
			jQuery( document ).scroll(function() {
				postDimensions();
			});
				
			setDimensions();

			function setDimensions() {
				msg = {};
				if (jQuery('#twine-iframe-none').length !== 0) {
					document.getElementById('twine-iframe-none').onload= function() {
						postDimensions();
					}
				} else {
					setTimeout(function() { setDimensions(); }, 150);	
				}
			}

			function postDimensions() {				
				var topDistance = jQuery(window).scrollTop();
				var windowHeight = document.documentElement.clientHeight;
				
				var aboveFeed = jQuery('#twine-iframe-none').offset().top;	
				
				document.getElementById('twine-iframe-none').contentWindow.postMessage(JSON.stringify({verb: "scroll-distance",data: {"topDistance": topDistance,"windowHeight": windowHeight,"aboveFeed":aboveFeed}}), "*");
			}
		},

		isaNumber: function (n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		},
	
		installListener: function (elem, eventName, fnc) {					
			if (elem.addEventListener){
				elem.addEventListener(eventName, fnc)
			} else {
				elem.attachEvent("on" + eventName, function (t) {
					fnc.call(this, t || this.e)
				});
			}
		},
		getElementByAttribute: function (attr, value, root) {
			root = root || document.body;
			if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
				return root;
			}
			var children = root.children, 
				element;
			for(var i = children.length; i--; ) {
				element = TwineSDK.getElementByAttribute(attr, value, children[i]);
				if(element) {
					return element;
				}
			}
			return null;
		},
		
		ShowDetail: function(id) {
			document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "show-detail",data: id}), "*");
		},
		
		load: function() {
			if (TwineSDK.getUrlParameter('loadWall') == "no") {
				return;
			}
			
			// we may have more than one script on this page			
			twineScripts = jQuery('script#twine-script,script[data-id="twine-script"]');
			for (scriptLoop = 0; scriptLoop < twineScripts.length; scriptLoop++) {				
				tScript = twineScripts[scriptLoop];
				instanceId = tScript.getAttribute('data-instance-id') || "none";
				
				if (!new RegExp(this.Base64.decode('L2JvdHxnb29nbGVib3R8Y3Jhd2xlcnxzcGlkZXJ8cm9ib3R8Y3Jhd2xpbmcvaQ==')).test(navigator.userAgent)) {
					jQuery(tScript).empty();
				}

				// figure out our domain name & append the format=embed tag
				src = tScript.src  + '&format=embed';

				pathArray = src.split( '/' );
				protocol = pathArray[0];
				host = pathArray[2];
				url = protocol + '//' + host;

				// if this is the first twine-script on the page, use it's URL to generate the
				// relative URL to load our embed.css from
				if (scriptLoop==0) {		
					// load in our CSS
					var cssLink = document.createElement("link");
					cssLink.rel = "stylesheet", cssLink.type = "text/css", cssLink.href = url + "/css/player/embed.css", document.getElementsByTagName("head")[0].appendChild(cssLink);

					TwineSDK.CreateTwineElements();
				}

				// split the URI elements
				var searchString = tScript.src;
				var request = {};
				var pairs = searchString.substring(searchString.indexOf('?') + 1).split('&');
				for (var i = 0; i < pairs.length; i++) {
					var pair = pairs[i].split('=');
					request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
				}

				// generate a unique ID for this frame
				iFrameID = "twine-iframe-" + instanceId;
	
				// only permit loading the twine iframe with this ID once per page
				if (document.getElementById(iFrameID)) {return;}


				// this is where the javascript loader sets the source for the IFRAME. It auto passes down any URL parameters sent in (cols=, tabs=, etc.).
         
				// build the new URL
				// we are stripping out the embed tag, but leaving in the rest of the parameters
				var nurl = src.replace('embed?app=' + request['app'] + '&',request['app'] + '?');
				nurl += "&eh=" + encodeURIComponent(document.location) + '&ref=' + encodeURIComponent(document.referrer) + '&ift=' + instanceId;

				// if the URL has a trailing series of digits then assume this is a post ID
				// pass this fragment in as a candidate. If this action class discovers that the layout
				// is using the host prefix, then we will assume that this is a post ID value
				if (window.location.hash && TwineSDK.isaNumber(window.location.hash.substring(1))) {
					nurl += '&postId=' + window.location.hash.substring(1);
				}
				
				if (TwineSDK.getUrlParameter('social-collection')) {
					nurl += '&collection=' + TwineSDK.getUrlParameter('social-collection');
				}					
				
				if (request['hideModals'] == 1) {					
					TwineSDK.HideModals = true;
				}										
				
				//TwineSDK.networks[msg.data.source].disableModal
				//TwineSDK.hidemorequest['width']==undefined ? "100%" : request['width']

				// load in the iFrame
				// we set the src of the new iFrame to nurl
				var f = document.createElement("IFRAME");
				f.width = request['width']==undefined ? "100%" : request['width'];
				f.id = iFrameID;
										
				if (typeof request['autoload'] == "undefined" || request['autoload'] == "auto") {
					f.height = "1000px";
				} else {
					f.height = typeof request['height']!=="undefined" ? request['height'] + 'px' : "1000px";
				}

				initialHeight = f.height;
				if (request['scroll'] == "no") {
					fixedHeight = (request['height']!="auto");
					f.scrolling = "yes";	// turn on iframe's native scrolling
				} else {
					fixedHeight = false;
					f.scrolling = "no";
				}
				
				if (request['autoload'] == "no") {
					Twine.autoLoadMore = false;
				} else {
					Twine.autoLoadMore = true;
				}

				f.seamless="seamless";
				f.allowScriptAccess="always";
				f.setAttribute('data-fixed-height',fixedHeight);
	
				// load it this way to avoid the white flash
				// if there is no src set, then unhide the iframe and load the src
				f.style.visibility="hidden";

				f.className ="twine-embed-iframe";
				f.frameBorder="0";
				

				if (TwineSDK.targetDiv==undefined || (document.getElementById(TwineSDK.targetDiv)==null)) {
					// they did not specify where exactly to load the hub, or what they specified does not exist,
					// so put it as the next sibling to the script
					tScript.parentNode.insertBefore(f, tScript.nextSibling);
				} else {
					document.getElementById(TwineSDK.targetDiv).appendChild(f);
				}

				if (f.attachEvent) {
					// support for IE8
					f.attachEvent('onload',function() {TwineSDK.setIFrameSrc(nurl,iFrameID)});
				} else {
					f.onload = TwineSDK.setIFrameSrc(nurl,iFrameID);
				}

				// maintain an internal array of frames
				Twine.frameArray.push({instanceId: instanceId, fixedHeight: fixedHeight, end: false});

			}

			jQuery(document).on('click', '#twine-modal-player a[data-action]',function(event){
				TwineSDK.ShareAction(this);				
			});

			// detect a scroll, and raise an event if necessary
			if (Twine.autoLoadMore) {
				TwineSDK.installListener(window,"scroll", function () {
				
					if (Twine.isBusy==1) {
						return;
					}

					// if we have < 600 pixels of content less and are not busy and are not a fixed iFrame size, send a message into the IFRAME
					// to get more
					if ((TwineSDK.SizerHeight() - TwineSDK.getPageOffset() - TwineSDK.getPageHeight()) < 600) {
						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							if (!Twine.frameArray[scriptLoop].end && document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).getAttribute('data-fixed-height')=="false") {
								Twine.isBusy=1;
								document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).contentWindow.postMessage(JSON.stringify({verb: "get-new-post",data: "load-from-parent"}), "*");
							}
						}
					}
				});
			}

			Twine.isBusy=0;				
				
		},

		getUrlParameter: function(sParam) {
			// from http://stackoverflow.com/questions/19491336/get-url-parameter-jquery
			var sPageURL = window.location.search.substring(1);
			var sURLVariables = sPageURL.split('&');
			for (var i = 0; i < sURLVariables.length; i++) 
			{
				var sParameterName = sURLVariables[i].split('=');
				if (sParameterName[0] == sParam) 
				{
					return sParameterName[1];
				}
			}
		},		

		loadScript: function(url) {
			var script = document.createElement("script")
			script.type = "text/javascript";

			if (script.readyState){  //IE
				script.onreadystatechange = function(){
					if (script.readyState == "loaded" || script.readyState == "complete"){
						script.onreadystatechange = null;
						TwineSDK.allReady();
					}
				};
			} else {  //Others
				script.onload = function(){
					TwineSDK.allReady();
				};
			}
			script.src = url;
			document.getElementsByTagName("head")[0].appendChild(script);
		},
		
		allReady: function() {

			// jQuery is available to us.
			// finish setup, then proceed to init()
			// merge in their TwineOptions config options, if any
			if (typeof TwineOptions !== 'undefined') {
				jQuery.extend(true,TwineSDK, TwineOptions);
			}

			// do we auto-init?
			if (this.autoLoad==true && typeof TwineConfig == 'undefined') {
				this.init();
			}
		},
		
		ShowPostCreator: function() {		
			TwineSDK.HideModals();
			document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "show-post-creator",data: ""}), "*");
		},
		
		fadeInPostCreatorModal: function(msg) {
			m = msg.data.data;

			var i = document.getElementById("twine-modal-background");
			jQuery(i).delay(0).fadeIn(200);

			viewPort = TwineSDK.getViewport();

			var j = document.getElementById("twine-modal-creator");
			
			j.innerHTML = msg.data.html;

			var f = document.getElementById("twine-modal-creator-content");
			f.onload = function() {
				var g = document.getElementById("twine-modal-creator-content");
				jQuery(g).fadeIn(100);
				TwineSDK.installListener(document.getElementById('twine-modal-background'),'click',function() {
					document.getElementById('twine-modal-creator').style.display="none";
					document.getElementById('twine-modal-background').style.display="none";
					jQuery('#twine-modal-background').clearQueue();

					}
				);		
			};

			f.style.display="none";
			f.src = msg.data.url;
			f.frameBorder="0";
			f.width="100%";

			jQuery(j).fadeIn(100);			
		
			TwineSDK.MinimizeToolbar();
								
		},
		
		ShowModalPrompt: function(msg) {
			document.getElementById('prompt-inner').innerHTML = msg.data.html;

			var i = document.getElementById("twine-modal-background");
			jQuery(i).delay(0).fadeIn(300);

			viewPort = TwineSDK.getViewport();

			var j = document.getElementById("twine-modal-prompt");
			
			jQuery(j).fadeIn(100, function() {
				jQuery(document).on('click', '#twine-modal-prompt a[data-action]',function(event){
					TwineSDK.ShareAction(this);				
				});
		
				TwineSDK.MinimizeToolbar();
			
				TwineSDK.installListener(document.getElementById('twine-close'),'click',function() {
					jQuery('#twine-modal-prompt').fadeOut(150)
					jQuery('#twine-modal-prompt #prompt-inner').empty();				
					jQuery('#twine-modal-background').clearQueue();
					document.getElementById('twine-modal-background').style.display="none";
					parent.location.hash = "_";
				});

				TwineSDK.installListener(document.getElementById('twine-modal-background'),'click',function() {
					jQuery('#twine-modal-prompt #prompt-inner').empty();
					jQuery('#twine-modal-background').clearQueue();
					document.getElementById('twine-modal-background').style.display="none";
					parent.location.hash = "_";
				});		
					
			});
		},
		
		init: function() {
		
			var e = this;
			var n = 300;
			var r = 1500;
			var i = function (e, n) {
					var r = [],
						i = n && new RegExp("(^| )" + n + "( |$)"),
						s = this.document.getElementsByTagName(this),
						o = document.getElementsByTagName("link").length,
						u = n ? "." + n : "",
						a = 0,
						f, l;
					if (document.querySelectorAll) {
						l = document.querySelectorAll(e + u);
						for (a = 0, f = l.length; a < f; a++) r.push(l[a]);
						return r
					}
					for (; a < o; a++)(!n || i.test(s[a].className)) && r.push(s[a]);
					return r
				};


			// shim for IE9 cross domain
			// test to see if we are IE9 or lower
			if (document.all && !window.atob) {
				 // from https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
				(function(a){if(typeof define==='function'&&define.amd){define(['jquery'],a)}else{a(jQuery)}}(function($){if($.support.cors||!$.ajaxTransport||!window.XDomainRequest){return}var n=/^https?:\/\//i;var o=/^get|post$/i;var p=new RegExp('^'+location.protocol,'i');$.ajaxTransport('* text html xml json',function(j,k,l){if(!j.crossDomain||!j.async||!o.test(j.type)||!n.test(j.url)||!p.test(j.url)){return}var m=null;return{send:function(f,g){var h='';var i=(k.dataType||'').toLowerCase();m=new XDomainRequest();if(/^\d+$/.test(k.timeout)){m.timeout=k.timeout}m.ontimeout=function(){g(500,'timeout')};m.onload=function(){var a='Content-Length: '+m.responseText.length+'\r\nContent-Type: '+m.contentType;var b={code:200,message:'success'};var c={text:m.responseText};try{if(i==='html'||/text\/html/i.test(m.contentType)){c.html=m.responseText}else if(i==='json'||(i!=='text'&&/\/json/i.test(m.contentType))){try{c.json=$.parseJSON(m.responseText)}catch(e){b.code=500;b.message='parseerror'}}else if(i==='xml'||(i!=='text'&&/\/xml/i.test(m.contentType))){var d=new ActiveXObject('Microsoft.XMLDOM');d.async=false;try{d.loadXML(m.responseText)}catch(e){d=undefined}if(!d||!d.documentElement||d.getElementsByTagName('parsererror').length){b.code=500;b.message='parseerror';throw'Invalid XML: '+m.responseText;}c.xml=d}}catch(parseMessage){throw parseMessage;}finally{g(b.code,b.message,c,a)}};m.onprogress=function(){};m.onerror=function(){g(500,'error',{text:m.responseText})};if(k.data){h=($.type(k.data)==='string')?k.data:$.param(k.data)}m.open(j.type,j.url);m.send(h)},abort:function(){if(m){m.abort()}}}})}));
			}

			if (typeof TwineOptions == 'undefined' && typeof TwineConfig == 'undefined') {
				// they have not defined a TwineConfig object, so auto-load this hub when the page loads
				TwineSDK.installListener(window,"load", function() {
					TwineSDK.load();
				});
			} else {
				// they are using the TwineConfig object, so load the hub on the init() function call
				TwineSDK.load();
			}

			// startup as busy so we have time to load up this script
			Twine.isBusy=1;

			// detect a scroll, and raise an event if necessary
			TwineSDK.installListener(window,"resize", function () {
			
				viewPort = TwineSDK.getViewport();
				for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
					document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).contentWindow.postMessage(JSON.stringify({verb: "resized",data:{width: viewPort[0],height: viewPort[1]}}), "*");
				};
			});
			
			var addCSS = function() {
				var styleTag = document.createElement ("style");
				var head = document.getElementsByTagName ("head")[0];
				document.getElementsByTagName('head')[0].appendChild (styleTag);
				
				var rule = "body #twine-modal-player { max-height: " + jQuery(window).height() + "px !important; }";
				
				//console.log($.fn.jquery);

				var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;
				if (sheet.insertRule) {										
					sheet.insertRule(rule, 0);
				} else {				
					sheet.addRule(rule, 0);
				}
			};
			
			addCSS();
			
			TwineSDK.installListener(window,"resize", addCSS);

			// receive messages from our iFrame
			TwineSDK.installListener(window,"message", function (e) {

				if (e == undefined || e.data == undefined || typeof e.data=="object") {return;}

				// test if it smells like JSON
				if (e.data.substring(0,1)!=="{") {return;}
		
				msg = JSON.parse (e.data);
												
				   switch (msg.verb) {
				   case "ready":
				   		// Twine is all set and ready to go
						if (msg.target !== undefined) {
							document.getElementById('twine-iframe-' + msg.target).style.visibility = 'visible';

							// reply back with my viewport dimensions so that we can later size modals					
							viewPort = TwineSDK.getViewport();
							document.getElementById('twine-iframe-' + msg.target).contentWindow.postMessage(JSON.stringify({verb: "resized",data: {width: viewPort[0],height: viewPort[1]}}), "*");

							Twine.isBusy = 0;
						}
						break;
					case "ignored":
						Twine.isBusy = 0;
						break;
						
					case "vote-response":
						jQuery(".read_more_button").hide();
						jQuery("#modal_vote").html(msg.data.message).removeClass("twine-button");
						break;
						
					case "get-size-on-orientation-change":
						iframe = document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId);
						iframeParent = iframe.parentElement;
						iframeParentWidth = jQuery(iframeParent).width();
						jQuery(iframe).css({
							'width':iframeParentWidth + 'px'
						});
						
						document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId).contentWindow.postMessage(JSON.stringify({verb: "set-size-on-orientation-change",data: iframeParentWidth}), "*");						
						break;
					
					case "pass-in-parent-scroll-event":
						TwineSDK.passDimensionsToIFrame();
						break;
						
					case "go-url":
						location.href= (msg.data);
						break;
						
					case "reset-to-initial-frame-height":
						// this receives a message from the layout, resetting the initial height of the iframe
						document.getElementById('twine-iframe-' + msg.target).style.height = initialHeight;
						break;
						
					case "post-creator-send-viewport":
						document.getElementById('twine-modal-creator-content').contentWindow.postMessage(JSON.stringify({verb: "post-creator-send-viewport",data: TwineSDK.getViewport() }), "*");
						break;	
						
					case "main-iframe-send-viewport":
						document.getElementById('twine-iframe-none').contentWindow.postMessage(JSON.stringify({verb: "main-iframe-send-viewport",data: TwineSDK.getViewport() }), "*");
						break;						

					case "set-initial-frame-height":
						// this receives a message from the layout, setting the initial height of the iframe
						initialHeight = msg.data + "px";
						
						if (document.getElementById('twine-iframe-' + msg.target) != null) {
							document.getElementById('twine-iframe-' + msg.target).style.height = msg.data + "px";
						}
						break;

					case "minimize-toolbar" :
						TwineSDK.MinimizeToolbar();
						break;					
					case "destroy-toolbar" :
						TwineSDK.DestroyToolbar();
						break;

					case "expand-toolbar" :
						TwineSDK.ExpandToolbar();
						break;
					case "shrink-toolbar" :
						TwineSDK.ShrinkToolbar();
						break;

					case "hide-modals" :
						TwineSDK.HideModals();
						break;											

					case "update-design" :
						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).contentWindow.postMessage(JSON.stringify({verb: "update-design",data: msg.data}), "*");
						};
						break;

					case "new-posts" :
						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							if (Twine.frameArray[scriptLoop].instanceId == msg.target) {
								Twine.frameArray[scriptLoop].end = false;
							}
						}
						break;

					case "tile-event":
						// we clicked on a tile

						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).contentWindow.postMessage(JSON.stringify({verb: "tile-event", action: msg.action, data: msg.data}), "*");
						};

 						TwineSDK.HideModals();
				
					case "reloaded" :
						if (document.title.substr(0,1)=="(") {
							document.title = document.title.substr(document.title.indexOf(') ')+2);
						}

						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							if (Twine.frameArray[scriptLoop].instanceId == msg.target) {
								Twine.frameArray[scriptLoop].end = false;
							}
						}

						break;

					case "new-posts" :
						if (document.title.substr(0,1)=="(") {
							document.title = '(' + msg.data + ') ' + document.title.substr(document.title.indexOf(') ')+2);
						} else {
							document.title = '(' + msg.data + ') ' + document.title;
						}
						break;

					case "set-frame-height":
						// the iframe src loaded some more content internally
						// grow the dimensions of the iframe
						if (!fixedHeight) {
							document.getElementById('twine-iframe-' + msg.target).style.height = msg.data + "px";
						}

						Twine.isBusy = 0;
						break;

					case "no-more-items":
						// we have reached the end so stop trying on scroll
						for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
							if (Twine.frameArray[scriptLoop].instanceId == msg.target) {
								Twine.frameArray[scriptLoop].end = true;
							}
						}
						break;
						
					case "load-toolbar-content":
						// load toolbar content
						// the actual content is built by the embed frame and sent up here as a message
						var j = document.getElementById("twine-toolbar");
						j.innerHTML = msg.data.html;
						document.getElementById("twine-toolbar-content").src = msg.data.url;

						TwineSDK.InstallToolbarListeners();

						break;

					case "show-modal-editor":
					
						m = msg.data.data;

						// size the video player
						
						var i = document.getElementById("twine-modal-background");
						jQuery(i).delay(100).fadeIn(1000);

						viewPort = TwineSDK.getViewport();

						var j = document.getElementById("twine-modal-editor");
						j.innerHTML = msg.data.html;

						var f = document.getElementById("twine-modal-editor-content");
						f.onload = function() {
							var g = document.getElementById("twine-modal-editor-content");
							jQuery(g).fadeIn(500);
						};
						f.style.display="none";
						f.src = msg.data.url;


						j.style.marginLeft = "-" + parseInt(viewPort[0]-300)/2 + "px";

						jQuery(j).fadeIn(500);

						TwineSDK.installListener(document.getElementById('twine-modal-background'),'click',function() {
							document.getElementById('twine-modal-editor').style.display="none";
							document.getElementById('twine-video-iframe').src="";
							document.getElementById('twine-modal-background').style.display="none";
							jQuery('#twine-modal-background').clearQueue();

							}
						);

						TwineSDK.installListener(document.getElementById('twine-close'),'click',function() {
							document.getElementById('twine-modal-editor').style.display="none";
							document.getElementById('twine-modal-background').style.display="none";
							jQuery('#twine-modal-background').clearQueue();

							}
						);
					
						TwineSDK.MinimizeToolbar();
												
   						break;

					case "show-modal-creator":
						
						TwineSDK.fadeInPostCreatorModal(msg);
						
   						break;   
				
					case "show-modal-prompt":
						
						TwineSDK.ShowModalPrompt(msg);
						
   						break;   
				
					case "show-modal-player":
					
						if (typeof TwineSDK.HideModals !== 'undefined' && TwineSDK.HideModals == true || typeof TwineSDK.networks[msg.data.source] !== 'undefined' && TwineSDK.networks[msg.data.source].disableModal !== 'undefined' && TwineSDK.networks[msg.data.source].disableModal==true) {	
							!window.open(msg.data.sourceUrl,"_blank","menubar=no,height=600,width=600");
							//win.focus();														
						} else {
							// show the modal background
							var i = document.getElementById("twine-modal-background");
							jQuery(i).delay(1000).fadeIn(2000);

							var j = document.getElementById("twine-modal-player");
							//j.style.top = jQuery(document).scrollTop() + "px";
							j.style.display="none";

							parent.location.hash = msg.data.id;
							TwineSDK.MinimizeToolbar();
							
							var shareLinks = msg.data.shareLinks;
							
							j.innerHTML = msg.data.html;
							jQuery(j).fadeIn(500);	

							TwineSDK.installListener(document.getElementById('twine-close'),'click',function() {
								jQuery('#twine-modal-player').empty();
								jQuery('#twine-modal-background').clearQueue();
								document.getElementById('twine-modal-background').style.display="none";
								parent.location.hash = "_";
							});

							TwineSDK.installListener(document.getElementById('twine-modal-background'),'click',function() {
								jQuery('#twine-modal-player').empty();
								jQuery('#twine-modal-background').clearQueue();
								document.getElementById('twine-modal-background').style.display="none";
								parent.location.hash = "_";
							});														
							
							for (i = 0; i < document.querySelectorAll('[data-cta-action]').length; i++) {								
								TwineSDK.installListener(document.querySelectorAll('[data-cta-action]')[i],'click',function() {
									TwineSDK.executeCTAEvent(this);
								});															
							} 
														
							FB.XFBML.parse();
							
							if (document.getElementById('show-post-creator') !== null) {
								TwineSDK.installListener(document.getElementById('show-post-creator'),'click',function() {
									TwineSDK.HideModals();
									TwineSDK.ShowPostCreator();		
								});
							}
						}
   						break;
   						 					
					case "scroll-to-top":
						// scroll down to the specified offset, plus the offset of the iframe
						mt = jQuery('#twine-iframe-' + msg.target).offset().top; 
						innerHeight = window.innerHeight || document.documentElement.clientHeight;
						targetPos = Number(mt);
						jQuery('body,html').animate({scrollTop: targetPos -100});

						break;

					case "set-current-offsetTop":
						// scroll down to the specified offset, plus the offset of the iframe
						mt = jQuery('#' + Twine.iFrameID).offset().top; 
						innerHeight = window.innerHeight || document.documentElement.clientHeight;
						targetPos = Number(msg.data.elementTop) +  Number(mt) - (innerHeight/2) + (msg.data.elementHeight/2);
						jQuery('body,html').animate({scrollTop: targetPos});
						
						break;
					}
			});
		}
	};

	// if jQuery is not loaded, we add it
	// Wordpress sites include it by default
	if (typeof jQuery == 'undefined') {  
		TwineSDK.loadScript('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');				
	} else {
		TwineSDK.allReady();	
	}		
	
	try {
		jQueryVersion = parseFloat(jQuery.fn.jquery).toFixed(2);
		//if (jQueryVersion < 1.7) {
		
		//	console.log('TwineSocial Alert: You are using an old version of jQuery on your parent page. For best results with your TwineSocial embed, please upgrade to jQuery 1.10.2 or above. Download the latest version of jQuery here: https://code.jquery.com/jquery/');
		//}
	} catch(err) {}
	
	if (typeof FB == 'undefined') {  					
		(function(d, s, id){
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) {return;}
			js = d.createElement(s); js.id = id;
			js.src = "//connect.facebook.net/en_US/sdk.js";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));	
		
		window.fbAsyncInit = function() {
			FB.init({
				status     : true,
				xfbml      : true,
				version    : 'v2.4' // or v2.0, v2.1, v2.2, v2.3
			});
		}
	}

} else {
	// this script has already been loaded
	// probably have it 2x on the same page
}

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 */
(function() {
  if (!window.console) {
    window.console = {};
  }
  // union of Chrome, FF, IE, and Safari console methods
  var m = [
    "log", "info", "warn", "error", "debug", "trace", "dir", "group",
    "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
    "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
  ];
  // define undefined methods as noops to prevent errors
  for (var i = 0; i < m.length; i++) {
    if (!window.console[m[i]]) {
      window.console[m[i]] = function() {};
    }    
  } 
})();

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};