﻿(function() {

	var o = {
		// some config
		useAssetLoaders: false,
		scrollBarWidth: 16,




		// initialize some variables
		currentContent: 0,
		ingredients: false,
		scrollby: 1,
		useOverlaySource: false,
		dialogBehaviour: 1,
		voted_already: false,
		moreFlashes: 0,
		nextFlashes: 0,
		nextFlashTimeout: false,
		afterResizeTimeout: false,
		packID: 0,

		init: function(btVoteID, btShareID) {
			o.voteButtonId = btVoteID;
			o.shareButtonId = btShareID;
			if (BrowserDetect) {
				BrowserDetect.init();
				if (BrowserDetect.browser == 'Explorer') {
					o.useOverlaySource = true;
				}
			}


			$("#content-slider iframe:first").data('ord', 0);

			if (typeof EMPillData != 'undefined' && EMPillData !== null) {
				o.ingredients = EMPillData.contents;
				o.voted_already = EMPillData.voted_already;
				o.description = EMPillData.description;
				o.packID = EMPillData.pid;

				EMOTIFY.log('got pills');
				$(window).resize(o.watchResize);

				for (var i = 1; i < o.ingredients.length; i++) {
					$("#content-slider").append('<div class="content_item" id="content_frame_' + i + '"><div class="content_frame_holder"><iframe id="theiframe' + i + '" name="theiframe' + i + '" class="packItemFrame" frameborder="0" noresize="noresize" src="about:blank" allowtransparency="true" style="background:transparent;"></iframe></div></div>');
					$("#theiframe" + i).data('ord', i);
					o.ingredients[i].frameid = ('theiframe' + i);
					o.ingredients[i].containerid = ('content_frame_' + i);
				}


				o.setFrameSize();
				o.setFrameSize(); // twice for IE to deal with a scrollbar issue
				$("#content-slider .packItemFrame").css({ "visibility": "visible" });


				o.makeSummary(0);
				o.hideCurrentSummary(true, true);
				$("#centerZone").hoverIntent({ "over": o.showCurrentSummary, "out": function() { } });
				$("#content-area").mouseover(o.hideCurrentSummary);

				EMOTIFY.log('at nd of if');

			} else {
				// fail.
			}

			o.setIframeOnload('theiframe', function(e) { o.setLoaded(0); o.loadNext(); });
			o.ingredients[0].frameid = 'theiframe';
			o.ingredients[0].containerid = 'content_frame_0';

			EMOTIFY.log('setting up click handlers');
			// set up click handlers
			$("#next").bind('click', o.step);
			$("#prev").click(o.stepBack);
			EMOTIFY.log('click handlers ready');

			$("#more .share").click(o.startShare);

			$("#info").bind('click', o.showHideDescBubble);

			o.track();

			$("#share_widgets_car .widget").click(o.trackWidget);

		},

		watchResize: function() {
			if (o.afterResizeTimeout) {
				clearTimeout(o.afterResizeTimeout);
				setTimeout(function() { o.setFrameSize(); }, 100);
			}
		},

		startShare: function() {
			$("#" + o.shareButtonId).click();
		},

		trackWidget: function() {
			var t = $(this), widgetName = false;

			if (t.hasClass('facebook')) {
				widgetName = 'facebook';
			} else if (t.hasClass('twitter')) {
				widgetName = 'twitter';
			} else if (t.hasClass('digg')) {
				widgetName = 'digg';
			} else if (t.hasClass('addthis')) {
				widgetName = 'addthis';
			}

			if (widgetName) {
				o.track('share/' + widgetName);
			}

		},


		// build the tracking URL and track this action - for analytics.
		track: function(action, ord) {
			if (typeof ord == 'undefined' || ord === null) {
				ord = o.currentContent;
			}

			if ((ord + 1) >= o.ingredients.length) {
				ord = 'final';
			}

			if (typeof action == 'undefined' || action === null) {
				action = '';
			} else {
				action = '/' + action;
			}
			EMOTIFY.track('pack/' + o.packID + '/' + ord + action);
		},

		setVoted: function(voted) {
			if (voted === true) {
				o.voted_already = true;
				if ((o.currentContent + 1) == o.ingredients.length) {
					o.makeNextShare();
				}
			} else if (voted === false) {
				o.voted_already = false;
			}
		},

		setFrameSize: function() {
			EMOTIFY.log('setting size');


			var b, c, cs, cheight;
			b = $("#bar");
			c = $("#content-area");
			cs = $("#content-slider");
			cl = $("#content-loader");
			s = EMOTIFY.util.viewport();

			var width = c.innerWidth();
			o.scrollby = width;

			cheight = s[1] - b.outerHeight();
			c.css({ "height": cheight + "px" });
			cs.css({ "height": cheight + "px", "width": (width * o.ingredients.length) + "px", "left": (o.currentContent * o.scrollby * (-1)) + "px" });
			cl.css({ "height": cheight + "px", "lineHeight": cheight + "px" });

			$("#content-slider .content_item").css({ "height": cheight + "px", "width": width + "px", "position": "relative" });

			EMOTIFY.log('height set');

			var frames = document.getElementById('content-slider').getElementsByTagName('iframe');

			for (var i = 0; i < frames.length; i++) {

				if (frames[i].className.indexOf('packItemFrame') > -1) {
					$(frames[i]).parents('.content_item:first').css({ "position": "absolute", "left": (i * width) + "px" });
					frames[i].setAttribute('height', cheight);
					frames[i].setAttribute('width', width);
					$(frames[i]).css({ "width": width + "px" });
					o.sizeSummary(i);
				}
			}
		},


		drawIframe: function(ordinal) {
			if (!(typeof ordinal != 'undefined' && ordinal !== null)) {
				ordinal = o.currentContent + 1;
			}

			if (o.IsValid(ordinal)) {
				var f, jqf;

				if (document.getElementById(o.ingredients[ordinal].frameid)) {
					if (!o.isStarted(ordinal)) {
						if (!o.ingredients[ordinal].isBreakOutSite) {
							document.getElementById(o.ingredients[ordinal].frameid).src = o.ingredients[ordinal].url;
							o.setIframeOnload(o.ingredients[ordinal].frameid, function() { o.setLoaded(ordinal); });
						}
						EMOTIFY.log('iframe was ' + o.ingredients[ordinal].frameid + ' drawn');
						o.removeLoader(o.ingredients[ordinal].id);

						// show the overlay
						if ($("#" + o.ingredients[ordinal].containerid + ' .summary').length > 0) {
							$("#" + o.ingredients[ordinal].containerid + ' .summary').slideDown(0);

						} else {
							o.makeSummary(ordinal);
						}

					} else {
						EMOTIFY.log('did not draw iframe ' + o.ingredients[ordinal].frameid + ' (src already exists): ' + document.getElementById(o.ingredients[ordinal].frameid).src);
					}
				}
			}
		},

		isStarted: function(ord) {
			EMOTIFY.log('checking if started');
			if (o.IsValid(ord)) {
				var i, f;
				i = o.ingredients[ord];
				EMOTIFY.log('frameid ' + i.frameid);
				f = document.getElementById(i.frameid);
				EMOTIFY.log('src: ' + f.src);
				EMOTIFY.log('src type: ' + typeof f.src);
				EMOTIFY.log(f);

				if (typeof f.src !== 'undefined' && f.src !== null && f.src.length > 1 && f.src != 'about:blank') {
					EMOTIFY.log('started ------------------------');
					return true;

				}

			}

			EMOTIFY.log('not started -------------------------');
			return false;
		},


		setLoaded: function(ordinal) {
			EMOTIFY.log('setLoaded ' + ordinal + ' ++++++++++++++++++++++++++++++++++++');
			// && o.ingredients[ordinal].medium == 1
			//	&& o.ingredients[ordinal].geckofilm
			//			if (o.currentContent < ordinal && (o.ingredients[ordinal].isGeckoSite || (o.ingredients[ordinal].medium == 1 && o.ingredients[ordinal].url.indexOf('ytviewer') < 0))) {  // re-enstate when we have geckofilm
			//			if (o.currentContent < ordinal && o.ingredients[ordinal].url.indexOf('ytviewer') < 0) {
			if (o.currentContent < ordinal && (o.ingredients[ordinal].isGeckoSite || o.ingredients[ordinal].medium == 1)) {


				o.removeFrame(ordinal);
				o.ingredients[ordinal].hasloaded = true;
				o.sizeSummary(ordinal);
				EMOTIFY.log('-------------------- unloading');
			} else {
				o.ingredients[ordinal].loaded = true; // says if it is loaded now.
				o.ingredients[ordinal].hasloaded = true; // says if it has ever loaded.
				o.sizeSummary(ordinal);
				$("#content-loader").hide(0);

				if (o.ingredients[ordinal].url.indexOf('ytviewer') > -1) {
					// try to make this thing play
				}

			}

			if (o.currentContent == 0) {
				EMOTIFY.log('about to show tooltip');
				o.showIntroToolTip();

				EMOTIFY.log('setting timeout for next flasher');
				o.nextFlashTimeout = setTimeout(o.flashNext, 30000);
			}

		},

		ytReady: function(ord, player) {
			if (o.IsValid(ord)) {
				if (ord == o.currentContent) {
					player.playVideo();
				}
			}
		},

		ytPlay: function(ord) {
			if (o.IsValid(ord)) {
				if (o.ingredients[ord].url.indexOf('ytviewer') > -1) {
					var oIframe = document.getElementById(o.ingredients[ord].frameid);
					var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
					if (oDoc.document) oDoc = oDoc.document;
					if (oDoc.getElementById('ytplayer')) {
						oDoc.getElementById('ytplayer').playVideo();
					}
				}
			}
		},

		makeNextShare: function() {
			var elem;
			if ($("#next").length) {
				elem = $("#next");
				elem.unbind('click', o.step);
				elem.bind('click', o.startShare);
			} else if ($("#vote").length) {
				elem = $("#vote");
				elem.replaceWith('<a id="next" class="navButton enabled">next<span class="flasher"></span></a>');
				elem = $("#next");
				$("#next").bind('click', o.startShare);
			} else {
				return false;
			}
		},

		makeNextNext: function() {
			var elem = $("#next");
			elem.unbind('click', o.startShare);
			elem.bind('click', o.step);
		},


		loadNext: function(ord) {
			if (typeof ord == 'undefined' || ord == null) {
				if (o.IsValid(o.currentContent + 1)) {
					ord = o.currentContent + 1;
				} else {
					ord = false;
				}
			}


			if (ord) {
				var ingredient = o.ingredients[ord];

				if (ingredient.medium != 1 || ingredient.medium == 1) {
					o.drawIframe(ord);
				} else {
					// draw the asset loader for this content
					if (o.useAssetLoaders) {
						if (!ingredient.assetLoadAttempted && !document.getElementById('assetloader' + ingredient.id) && !ingredient.isBreakOutSite) {
							$("#assetloaders").append('<iframe id="assetloader' + ingredient.id + '" class="assetloader" frameborder="0" noresize="noresize" src="/assetloader.ashx?id=' + ingredient.id + '" width="10" height="10" allowtransparency="true" style="background:transparent;"></iframe>');



							o.ingredients[ord].assetLoadAttempted = true;
						}
					}
				}
			}
		},

		nextIsLoaded: function() {
			if ((o.currentContent + 1) < o.ingredients.length) {
				if (o.ingredients[o.currentContent + 1].loaded) {
					return true;
				}
			}

			return false;
		},

		nextIsStarted: function() {
			if (o.nextIsLoaded()) {
				return true;
			}

			var ord = o.currentContent + 1;
			if (o.IsValid(ord)) {
				if (document.getElementById(o.ingredients[ord].frameid)) {
					if (document.getElementById(o.ingredients[ord].frameid).src.length > 1) {
						return true;
					}
				}
			}
			return false;
		},

		prevIsLoaded: function() {
			if (o.currentContent > 0) {
				if (o.ingredients[o.currentContent - 1].loaded) {
					return true;
				}
			}
			return false;
		},

		prevIsStarted: function() {
			if (o.prevIsLoaded()) {
				return true;
			}
			var ord = o.currentContent - 1;
			if (o.IsValid(ord)) {
				if (document.getElementById(o.ingredients[ord].frameid)) {
					if (document.getElementById(o.ingredients[ord].frameid).src.length > 1) {
						return true;
					}
				}
			}
			return false;


		},

		makeBreakOutMessage: function(ord) {
			if (o.IsValid(ord)) {

				o.makeSummary(ord);
				var i, c;
				i = o.ingredients[ord];
				c = $("#" + i.containerid);

				if (c.find(".lightbox").length == 0) {

					var msg = $('<div class="lightbox breakout"><div class="lightbox_liner"><h2>Grumpy Site Alert!</h2><p>Long story short: <span class="title">' + decodeURIComponent(i.title) + '</span> doesn\'t want to be shown in the EmotiPack Viewer. To see it in a new tab/window <a href="' + decodeURIComponent(i.url) + '" target="_blank">Click Here</a> otherwise click next to skip.</p>');
					c.append(msg);
				}
				$("#content-loader").hide(0);

				o.setLoaded(ord);
			}
		},











		step: function() {
			if (o.nextFlashTimeout) {
				clearTimeout(o.nextFlashTimeout);
			}


			if ((o.currentContent + 1) < o.ingredients.length) {
				o.hideIntroToolTip(false);
				$("#content-loader").show(0);
				var topos = o.currentContent + 1;
				if (!o.ingredients[topos].isBreakOutSite) {
					if (!o.nextIsLoaded()) {
						EMOTIFY.log('drawing iframe');
						o.drawIframe(topos);
					} else {
						EMOTIFY.log('not drawing iframe');
					}
				} else {
					o.makeBreakOutMessage(topos);
				}


				$("#content-area").css({ "background": "none" });
				var cs = $("#content-slider:first");
				cs.animate({ "left": '-' + (topos * o.scrollby) + 'px' }, { "easing": "linear", "complete": function() { o.transitionComplete(topos, 'forward'); } });
				EMOTIFY.log('ani-forward');
				o.currentContent++;
			} else {
				o.startvote();
			}
		},

		stepBack: function() {
			if (o.currentContent > 0) {
				$("#content-loader").show(0);
				var topos = o.currentContent - 1;
				if (!o.prevIsLoaded()) {
					o.drawIframe(topos);
				}

				var cs = $("#content-slider:first");
				cs.animate({ "left": '-' + (topos * o.scrollby) + 'px' }, { "easing": "linear", "complete": function() { o.transitionComplete(topos, 'backward'); } });
				EMOTIFY.log('ani-backward');
				o.currentContent--;


			}
		},


		transitionComplete: function(ord, dir) {

			// find out if we went backwards or forwards.
			EMOTIFY.log('transition complete: ' + ord + ', ' + dir);

			o.track(null, ord);


			if (dir == 'forward') {
				// we went forward


				if (o.IsValid(ord - 1)) {
					//					if (o.ingredients[(ord - 1)].medium == 1 || !o.ingredients[(ord - 1)].hasloaded) {
					o.removeFrame((ord - 1));
					//					}
				}

				//				o.currentContent++;

				if ((ord + 1) == o.ingredients.length) {
					if (!o.voted_already) {
						//						$("#next").replaceWith('<a id="vote" class="navButton">Vote</a>');
						//						$("#vote").click(o.startvote);
					} else {
						o.makeNextShare();
					}
				}

			} else {

				if (o.IsValid(ord + 1)) {
					if (o.ingredients[ord + 1].medium == 1) {
						o.removeFrame(ord + 1);
					}

					if (o.IsValid(ord + 2)) {
						o.removeFrame(ord + 2);
					}
				}

				EMOTIFY.log('decrement');
				//				o.currentContent--;

				if ($("#vote").length > 0) {
					$("#vote").replaceWith('<a id="next" class="navButton enabled">Next<span class="flasher"></span></a>');
					$("#next").bind('click', o.step);
				} else {
					if ((ord + 2) == o.ingredients.length) {
						o.makeNextNext();
					}
				}
			}


			if ((ord + 1) == o.ingredients.length) {
				$("#positionWrapper").html('<span class="link">Vote</span>');
				$("#positionWrapper span").click(o.startvote);

			} else {
				$("#positionWrapper").html('<span id="currentPos">' + (ord + 1) + '</span> of ' + o.ingredients.length);
			}




			if (o.ingredients[ord].loaded) {
				o.loadNext();
				o.ytPlay(ord);
			} else {

				if (o.IsValid(ord)) {
					EMOTIFY.log('ord: ' + ord);
					EMOTIFY.log('current contents id: ' + o.ingredients[ord].frameid);
					o.setIframeOnload(o.ingredients[ord].frameid, function() { o.setLoaded(ord); o.loadNext(); });
				}
			}

			if ($("#next").length && (ord + 1) < o.ingredients.length) {
				if (!$("#next").hasClass('enabled')) {
					$("#next").addClass('enabled');
				}
			} else {
				//				$("#next").removeClass('enabled');
			}

			if (!$("#prev").hasClass('enabled') && ord > 0) {
				$("#prev").addClass('enabled');
			} else if (ord == 0) {
				$("#prev").removeClass('enabled');
			}






		},

		IsValid: function(ord) {
			if ((ord + 1) <= o.ingredients.length && ord >= 0) {
				return true;
			}
			return false;

		},

		removeFrame: function(ordinal) {

			if (o.IsValid(ordinal)) {
				if (o.removeIFrame(o.ingredients[ordinal].frameid)) {
					o.ingredients[ordinal].loaded = false
				}
			}
		},

		removeIFrame: function(id, remove) {
			if (document.getElementById(id)) {
				o.setIframeOnload(id, null);
				document.getElementById(id).src = 'about:blank';


				if (remove) {
					$(document.getElementById(id)).remove();
				} else {
					var old = $("#" + id);
					var nf = $('<iframe class="packItemFrame" name="' + old.attr('name') + '" frameborder="0" noresize="noresize" src="about:blank" allowtransparency="true" ></iframe>');

					nf.attr('id', old.attr('id'));
					nf.attr('style', old.attr('style'));
					nf.css({ "width": old.css('width'), "height": old.css("height") });
					$("#" + id).replaceWith(nf);
				}
				return true;
			}
			return false;
		},

		removeLoader: function(id) {
			o.removeIFrame('assetloader' + id, true);
		},

		getOrdFromFrame: function(frame) {
			for (var i = 0; i < o.ingredients.length; i++) {
				if (frame.getAttribute('id') == o.ingredients[i].frameid) {
					return i;
				}
			}
		},

		makeSummary: function(ord) {
			if (o.IsValid(ord)) {
				var i = o.ingredients[ord];
				var item = $("#" + i.containerid);
				var src = '';
				if (o.useOverlaySource) {
					src = '/packoverlaysource.htm';
				}


				item.append('<iframe class="summary_shim shim" scrolling="no" src="' + src + '" frameborder="0" noresize="noresize" height="120"></iframe>');
				item.append('<div class="summary_wrap"><div class="summary"><div class="liner"><h4>' + decodeURIComponent(i.title) + '</h4><p>' + decodeURIComponent(i.description) + '</p><a class="summary_close">hide</a></div></div></div>');
				item.find('.summary_close').click(o.hideSummary);

				o.sizeSummary(ord);
			}

		},

		sizeSummary: function(ord) {
			if (typeof ord == 'undefined' || ord === null) {
				ord = o.currentContent;
			}
			if (o.IsValid(ord)) {
				var adjustment = 0;
				if (o.ingredients[ord].loaded && !o.ingredients[ord].isBreakOutSite) {
					adjustment = o.scrollBarWidth;
				}

				if (adjustment > 0) {
					var cont = $("#" + o.ingredients[ord].containerid);
					cont.find('.summary_wrap:first').css({ "width": (cont.innerWidth() - adjustment) + "px" });

					var shim = $("#" + o.ingredients[ord].containerid + ' .summary_shim');
					shim.css({ "width": (cont.innerWidth() - adjustment) + "px" });
				}
			}
		},

		showCurrentSummary: function(e) {
			EMOTIFY.log('showCurrentSummary');
			if (e) {
				EMOTIFY.log('e target: ');
				EMOTIFY.log(e.target);
				if (o.ingredients[o.currentContent].loaded) {
					$("#" + o.ingredients[o.currentContent].containerid + " .summary_wrap").slideDown();
					$("#" + o.ingredients[o.currentContent].containerid + " .summary_shim").slideDown();
				}
			}
		},

		hideCurrentSummary: function(e, force) {
			if (e) {
				if (!(typeof force !== 'undefined' && force !== null && force === true)) {
					force = false
				}

				if ((e.pageY > 136 && o.ingredients[o.currentContent].loaded) || force) {
					$("#" + o.ingredients[o.currentContent].containerid + " .summary_wrap").slideUp();
					$("#" + o.ingredients[o.currentContent].containerid + " .summary_shim").slideUp();
				}
			}
		},

		hideSummary: function() {

			var p = $(this).parents('.content_item:first');
			p.find('.summary_wrap').slideUp();
			p.find('.summary_shim').slideUp();
			o.track('hidesummary');
		},

		startvote: function() {
			if ($("#" + o.voteButtonId).length) {
				$("#" + o.voteButtonId).click();
			}
		},

		getLightboxBehaviour: function() {
			var behaviour = 1;
			if (BrowserDetect) {
				if (!BrowserDetect.browser) {
					BrowserDetect.init();
				}

				if (BrowserDetect.browser == 'Explorer') {
					if (o.ingredients[o.currentContent].url.indexOf('youtube') > -1) {
						behaviour = 2;
					}
				}

				if (BrowserDetect.OS == 'Windows' && (BrowserDetect.browser == 'Chrome' || BrowserDetect.browser == 'Safari')) {
					if (o.ingredients[o.currentContent].url.indexOf('youtube') > -1) {
						behaviour = 3;
					}
				}
			}
			return behaviour;

		},


		lightbox: function(divisor) {
			EMOTIFY.log('lightboxing');

			// determine the behaviour
			var behaviour = 1, needsShim = false;
			behaviour = o.getLightboxBehaviour();

			if (o.ingredients[o.currentContent].url.indexOf('youtube') > -1) {
				needsShim = true;
			}

			if (typeof divisor == 'undefined' || divisor === null) {
				divisor = 2;
			}



			// determine the size of the lightbox and center itvertically.
			var lb, size, viewport, top;
			lb = $("#pnlLightBoxes .lightbox:first");
			if (lb.length) {

				lb.css({ "display": "block" });

				// see if this is a signup form and adjust the class of the lightbox accordingly
				if (lb.find('.logup').length > 0) {
					lb.addClass('logup');
					o.track('signup');
				} else {
					lb.removeClass('logup');
					if (lb.find('.loginLogup.login').length > 0) {
						o.track('login');
					}
				}



				size = [lb.outerWidth(), lb.outerHeight()];
				viewport = EMOTIFY.util.viewport();
				top = Math.floor(viewport[1] / divisor - size[1] / 2);
				if (top < 0) {
					top = 10;
				}

				lb.css({ "top": top + "px", "marginLeft": "-" + (Math.floor(size[0] / 2)) + "px" });


				if (behaviour === 1) {
					o.dialogBehaviour = 1;
					if (!$('#modalbg').length) {
						if (needsShim) {
							$('body:first').append('<iframe id="modalshim" frameborder="0" allowtransparency="true" noresize="noresize" src=""></iframe">');
						}

						$('body:first').append('<div id="modalbg"></div>');
					}

				} else if (behaviour === 2) {
					o.dialogBehaviour = 2;
					var pos, par;

					pos = lb.offset();
					var shim;

					if ($("#lightbox_shim").length == 0) {
						var shimstr = '<iframe src="" width="' + size[0] + '" height="' + size[1] + '" scrolling="no" frameborder="0" noresize="noresize" height="120" class="shim" id="lightbox_shim"></iframe>';
						shim = $(shimstr);
						shim.css({ "left": pos.left + "px", "top": pos.top + "px", "width": size[0] + "px", "height": size[1] + "px", "position": "absolute" });
						shim.insertAfter("#content-area:first");
					} else {
						shim.css({ "left": pos.left + "px", "top": pos.top + "px", "width": size[0] + "px", "height": size[1] + "px", "position": "absolute" });
					}

					if (!$('#modalbg').length) {
						$('body:first').append('<div id="modalbg"></div>');
					}


				} else if (behaviour === 3) {
					if ($("#modalbg").length == 0) {
						o.hideCurrentSummary();
						$("#content-loader").hide(0);
						$('body:first').append('<div id="modalbg"></div>');
						o.dialogBehaviour = 3;
						var h = $("#content-area").innerHeight() - 70;
						$("#content-slider").animate({ "top": h + "px" });
					}
				}

				//				alert('stop');
				var bodyHeight = $("html:first").height();
				lb = $("#pnlLightBoxes .lightbox:first");
				var lbTotalHeight = lb.outerHeight() + top;
				EMOTIFY.log('lb.outerheight: ' + lb.outerHeight() + '  top: ' + top);
				EMOTIFY.log('bodyheight: ' + bodyHeight + '  lbTotal: ' + lbTotalHeight);
				if (bodyHeight < lbTotalHeight) {
					bodyHeight = lbTotalHeight;
				}

				EMOTIFY.log('body height: ' + bodyHeight);
				$("#modalshim").css({ "height": bodyHeight + "px" });
				/*				$("#modalbg").css({ "height": bodyHeight + "px" });  */

				EMOTIFY.log('lightboxed');

				$("#pnlLightBoxes .lightbox .closeButton").click(o.delightbox);
			}
		},

		delightbox: function() {
			EMOTIFY.log('delightboxing');
			o.parkShareWidgets();

			var lb = $("#pnlLightBoxes .lightbox:visible");
			if (lb.length) {
				lb.css({ "display": "none" });
			}
			$("#modalbg").remove();
			$("#lightbox_shim").remove();
			$("#modalshim").remove();

			var behaviour = o.getLightboxBehaviour();
			if (behaviour == 3) {
				$("#content-slider").animate({ "top": "0px" });
			}

			if (typeof EMOTIFY.packviewer != 'undefined' && EMOTIFY.packviewer !== null) {
				EMOTIFY.log('to flash...');
				EMOTIFY.packviewer.flashMorePacks();
			} else {
				EMOTIFY.log('this is not going to work');
			}
		},

		getShareWidgets: function() {
			if (document.getElementById('share_widgets') && document.getElementById('share_widgets_car')) {
				document.getElementById('share_widgets').appendChild(document.getElementById('share_widgets_car'));
			}
		},

		parkShareWidgets: function() {
			if (document.getElementById('share_widgets_parking') && document.getElementById('share_widgets_car')) {
				document.getElementById("share_widgets_parking").appendChild(document.getElementById('share_widgets_car'));
			}
		},


		showHideDescBubble: function(e) {
			var b = $('body:first');
			var t = $(this);
			if (b.find('.description_bubble').length == 0) {
				o.track('info');

				var bubble = $('<div class="description_bubble"><div class="description_bubble_liner">' + decodeURIComponent(o.description) + '</div></div>');
				bubble.css({ "left": ((t.offset().left + 9) - 377) + "px" });
				b.append(bubble);
				b.bind('click', o.showHideDescBubble);
			} else {
				b.find('.description_bubble').remove();
				b.unbind('click', o.showHideDescBubble);
			}
			e.stopPropagation();
		},

		showIntroToolTip: function() {
			EMOTIFY.log('showing tooltip');
			if (EMOTIFY.util.cookie.read('seenEmotiPackTT') == '1') {
				// if we've seen the cookie, update it so it is still in place.
				EMOTIFY.util.cookie.create('seenEmotiPackTT', '1', 15);
			} else {
				$("#bar").append('<div class="introToolTipContainer"><div class="introToolTip">Click <img src="/img/pack-callout-arrow.png" width="20" height="19" alt="Image of a navigation button" title="Click this arrow" /> to see the next part of this package<a class="dismiss">[close]</a><span class="pointer"></span></div></div>');

				var tt = $("#bar .introToolTip:first");
				tt.find('.dismiss').click(function() { o.hideIntroToolTip(true); });

				var ttc = $("#bar .introToolTipContainer:first");
				ttc.slideDown('slow');
			}

		},

		hideIntroToolTip: function(setCookie) {

			$('#bar>.introToolTipContainer').slideUp('slow');

			// set the cookie
			if (setCookie) {
				EMOTIFY.util.cookie.create('seenEmotiPackTT', '1', 15);
			}
			o.track('hidepvcallout');
		},

		setIframeOnload: function(frameid, onload) {
			if (document.getElementById(frameid)) {
				if (document.frames) {
					//document.getElementById(frameid).onload = onload;
					//$addHandler(document.getElementById(frameid), 'load', onload);
					if (onload === null || typeof onload == 'undefined') {
						$("#" + frameid).unbind('load');
					} else {
						$("#" + frameid).bind('load', onload);
					}
				} else {
					document.getElementById(frameid).onload = onload;
				}
			}
		},

		flashMorePacks: function() {
			o.moreFlashes = 0;
			if (o.currentContent == (o.ingredients.length - 1)) {
				EMOTIFY.log('going to flash');
				o.doFlashMorePacks();
			} else {
				EMOTIFY.log('cannot flash');
			}
		},

		doFlashMorePacks: function() {
			if (o.moreFlashes < 5) {
				$("#more .gleam").fadeTo(500, 0.9, function() { $(this).fadeTo(500, 0, o.doFlashMorePacks); });
				o.moreFlashes++;
			}
		},

		flashNext: function() {
			o.nextFlashes = 0;
			if (o.currentContent < (o.ingredients.length - 1)) {
				EMOTIFY.log('going to flash next');
				o.doFlashNext();
			} else {
				EMOTIFY.log('cannot flash next');
			}
		},

		doFlashNext: function() {
			if (o.nextFlashes < 5) {
				$("#next .flasher").fadeTo(500, 0.9, function() { $(this).fadeTo(500, 0, o.doFlashNext); });
				o.nextFlashes++;
			}
		}

	}

	EMOTIFY.namespace('packviewer');
	EMOTIFY.packviewer = o;

})();
