/* Developed by Joel Davis of Yellow Button */

/* jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
http://jquery.thewikies.com/swfobject */
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

// when document is ready
$(function() {
   // "tell" the document that javascript is enabled.
   	$('HTML').addClass('JS');
	
	// hide the first video in a gallery
	$('a[rel*=gallery]:first').closest('.vidframe').hide();

	var idRgx = new RegExp(/(?:v=)([a-zA-Z0-9_\-]+)/i);

	// enable video buttons
	$("a[rel*=vid]").each(function(){
		var href = $(this).attr('href');
		var id = String(idRgx.exec(href).pop());
		var embedhref = 'http://www.youtube.com/v/' + id + '&amp;autoplay=1&amp;hl=en_US&amp;fs=1&amp;hd=1&amp;color1=0x938d80&amp;color2=0xcfc8b9&amp;showinfo=0';
		
		$(this).click(function(event){
			event.preventDefault();
	
			if ($.flash.available) {
				var frame = $(event.target).closest('.vidframe');
				var frameh = frame.height();
				var framew = frame.width();

				// track in GA
				_gaq.push(['_trackEvent', 'Video', 'PlayEmbedded', href]);

				// setup params
				var params = {
					swf     : embedhref, // tricky. This is writen on page load, not on click
					width   : framew,
					height  : frameh,
					allowFullScreen: true,
					id      : 'ytplayer-' + id
				};
				
				// set height and width to prevent resizing
				frame.height(frameh)
					.width(framew)
					// hide for later 
					//.wrapInner('<div class="replaced" id="v-' + id + '" />')
					.empty()
					//replace with video
					.flash(params);
			} else {
				// no flash (iOS)

				// track in GA
				_gaq.push(['_trackEvent', 'Video', 'PlayNoFlash', href]);

				document.location.href = href;
			}
		});
	}); 	

	//enable expandable FAQs
	$(".faq dd").hide();
	$(".faq dt").click().toggle(function() {
		_gaq.push(['_trackEvent', 'FAQ', 'Expand', $(this).text()]);
		$(this).next().slideDown(500);
	}, function() {
		_gaq.push(['_trackEvent', 'FAQ', 'Contract', $(this).text()]);
		$(this).next().slideUp(200);
	});


	// enable frontpage video gallery
	$("a[rel*=gallery]").each(function(){
		var href = $(this).attr('href');
		var id = String(idRgx.exec(href).pop());
		var embedhref = 'http://www.youtube.com/v/' + id + '&amp;autoplay=1&amp;hl=en_US&amp;fs=1&amp;hd=1&amp;color1=0x938d80&amp;color2=0xcfc8b9&amp;showinfo=0';
		
		$(this).click(function(event){
			event.preventDefault();
	
			if ($.flash.available) {
				var frame = $('#vidgalleryfeat');
				var frameh = frame.height();
				var framew = frame.width();
				var clickedframe = $(event.target).closest('.vidframe');

				// track in GA
				_gaq.push(['_trackEvent', 'Video', 'PlayEmbedded', href]);

				// setup params
				var params = {
					swf     : embedhref, // tricky. This is writen on page load, not on click
					width   : framew,
					height  : frameh,
					allowFullScreen: true,
					id      : 'ytplayer-' + id
				};

				// provide visual of transfer
				clickedframe.effect("transfer",{ to: frame, className: 'ui-effects-transfer' }, 500, function(){
					// set height and width to prevent resizing
					frame.height(frameh)
						.width(framew)
						// hide for later 
						.empty()
						//replace with video
						.flash(params);

					// show / hide gallery videos
					$("a[rel*=gallery]").closest('.vidframe').filter(':hidden').css("background", "#fff").slideDown(1000); //show('slide',{direction: 'down'}, 2000);
					clickedframe.css("background", "fff").slideUp(1000); //hide('slide', {direction: 'up'}, 2000, function(){
				});

			} else {
				// no flash (iOS)

				// track in GA
				_gaq.push(['_trackEvent', 'Video', 'PlayNoFlash', href]);

				document.location.href = href;
			}
	
		});
	});

	// make external links open in a new window and trackable in GA
	$("a[href^='http']:not([href*='wherethehellismatt.com']):not([rel*=vid]):not([rel*=gallery])")
		.addClass('external')
		.attr('target', '_blank')
		.click(function(){
			_gaq.push(['_trackEvent', 'External', 'Link', $(this).attr('href')]);
		});

	// track email links in GA
	$("a[href^='mailto']").click(function () {
		var email = $(this).attr('href').replace('mailto:', '');
		_gaq.push(['_trackEvent', 'External', 'E-mail', email]);
	});

	// track form submission in GA
	$('form').each(function(){
		var frmact = $(this).attr('action');	
		$(this).find('input:submit').click(function () {
			_gaq.push(['_trackEvent', 'Form', 'SubmitClick', frmact]);
		});
	});

});


