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;
			}
		},
		HideModals: function() {
			document.getElementById('twine-modal-player').style.display="none";
			document.getElementById('twine-modal-editor').style.display="none";


			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="";
			}

			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);


			// 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) {
			for (scriptLoop = 0; scriptLoop < Twine.frameArray.length; scriptLoop++) {
				document.getElementById('twine-iframe-' + Twine.frameArray[scriptLoop].instanceId).contentWindow.postMessage(JSON.stringify({verb: "share-action",data:{element: jQuery(element)[0].outerHTML}}), "*");
			};
		},
		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();
		},		
		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)];
		},

		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;
		},
		load: function() {

			// 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 (request['autoload'] == undefined || request['autoload'] == "auto") {
					f.height = "1000px";
				} else {
					f.height = request['height']==undefined ? "1000px" : request['height'] + 'px';
				}		

				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: ""}), "*");
							}
						}
					}
				});
			}

			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();
			}
		},
		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]}}), "*");
				};
			});


			// 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 "get-size-on-orientation-change":
						iframe = document.getElementById('twine-iframe-' + Twine.frameArray[0].instanceId);
						iframeParent = iframe.parentElement;
						iframeParentWidth = $(iframeParent).width();

						$(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 "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 "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
//						console.log ('embed receives tile event with action ' + msg.action);

						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-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) {
							function OpenInNewTab(url) {
								var win = window.open(url, '_blank');
								win.focus();
							}
							OpenInNewTab(msg.data.sourceUrl);																
						} 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();
							
							// get this story from the server
							jQuery.ajax({
								url: ('https:' == document.location.protocol ? 'https:' : 'http:') + msg.data.dataUrl,
								success: function(data) {

									j.innerHTML = data;
									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 = "_";
									});
 

								},
								error: function(jqXHR, textStatus, errorThrown) {
									console.log ('unable to display post: ' + textStatus)
									console.log (errorThrown);
									jQuery('#twine-modal-background').clearQueue();
									document.getElementById('twine-modal-background').style.display="none";
								}							
							});						
						}
								
   						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();
	}

} 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() {};
    }    
  } 
})();
