
// 'stacks' is the Stacks global object.
// All of the other Stacks related Javascript will 
// be attatched to it.
var stacks = {};


// this call to jQuery gives us access to the globaal
// jQuery object. 
// 'noConflict' removes the '$' variable.
// 'true' removes the 'jQuery' variable.
// removing these globals reduces conflicts with other 
// jQuery versions that might be running on this page.
stacks.jQuery = jQuery.noConflict(true);

// Javascript for stacks_in_1020_page5
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_1020_page5 = {};

// A closure is defined and assined to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for refering
// to this object from elsewhere.
stacks.stacks_in_1020_page5 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	


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




$(document).ready(function() {

// Setup some vars from user choices, plist vars

var chromeclose = "files/images/close.png";
var doooverlaycolour = "#000000";
var doooverlaytransparency = "2";
var popupwidth = "800";

                switch (doooverlaytransparency) {
                	case "0":
                        doooverlaytransparency = "1";
                        break;
                    case "1":
                        doooverlaytransparency = "0.9";
                        break;
                    case "2":
                        doooverlaytransparency = "0.8";
                        break;  
					case "3":
                        doooverlaytransparency = "0.7";
                        break;
                    case"4":
                        doooverlaytransparency = "0.6";
                        break;
                    case "5":
                        doooverlaytransparency = "0.5";
                        break;
                    case "6":
                        doooverlaytransparency = "0.4";
                        break;
                    case "7":
                        doooverlaytransparency = "0.3";
                        break;
                    case "8":
                        doooverlaytransparency = "0.2";
                        break;
                    case "9":
                        doooverlaytransparency = "0.1";
                        break;
                    default:
                        doooverlaytransparency = "0.9";
                };



// Chromless Player Functions

(function($){
	
	$.fn.stacks_in_1020_page5youTubeEmbed = function(settings){
	
	
		
		// Settings can be either a URL string,
		// or an object
		
		if(typeof settings == 'string'){
			settings = {'video' : settings}
		}
		
		// Default values
		
		var def = {
			width		: 640,
			progressBar	: true
		};
		
		settings = $.extend(def,settings);
		
		var stacks_in_1020_page5elements = {
			stacks_in_1020_page5originalDIV	: this,	// The "this" of the plugin
			stacks_in_1020_page5container	: null,	// A container div, inserted by the plugin
			stacks_in_1020_page5control		: null,	// The control play/pause button
			stacks_in_1020_page5player		: null,	// The flash player
			progress	: null,	// Progress bar
			elapsed		: null	// The light blue elapsed bar
		};
		

		try{	

			settings.videoID = settings.video.match(/v=(.{11})/)[1];
			
			// The safeID is a stripped version of the
			// videoID, ready for use as a function name

			settings.safeID = settings.videoID.replace(/[^a-z0-9]/ig,'');
		
		} catch (e){
			// If the url was invalid, just return the "this"
			return stacks_in_1020_page5elements.stacks_in_1020_page5originalDIV;
		}

		// Fetch data about the video from YouTube's API

		var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';

		$.get(youtubeAPI,{'q':settings.videoID},function(response){
			
			var data = response.data;
	
			if(!data.totalItems || data.items[0].accessControl.embed!="allowed"){
				
				// If the video was not found, or embedding is not allowed;
				
				return stacks_in_1020_page5elements.stacks_in_1020_page5originalDIV;
			}

			// data holds API info about the video:
			
			data = data.items[0];
			
			settings.ratio = 3/4;
			if(data.aspectRatio == "widescreen"){
				settings.ratio = 9/16;
			}
			
			settings.height = Math.round(settings.width*settings.ratio);

			// Creating a container inside the original div, which will
			// hold the object/embed code of the video

			stacks_in_1020_page5elements.stacks_in_1020_page5container = $('<div>',{className:'stacks_in_1020_page5flashContainer',css:{
				width	: settings.width,
				height	: settings.height
			}}).appendTo(stacks_in_1020_page5elements.stacks_in_1020_page5originalDIV).stacks_in_1020_page5_lightbox();
			 
			

			// Embedding the YouTube chromeless player
			// and loading the video inside it:

			stacks_in_1020_page5elements.stacks_in_1020_page5container.flash({
				swf			: 'http://www.youtube.com/apiplayer?enablejsapi=1&version=3',
				id			: 'video_'+settings.safeID,
				height		: settings.height,
				width		: settings.width,
				allowScriptAccess:'always',
				wmode		: 'transparent',
				flashvars	: {
					"video_id"		: settings.videoID,
					"playerapiid"	: settings.safeID
				}
			});

			// We use get, because we need the DOM element
			// itself, and not a jquery object:
			
			stacks_in_1020_page5elements.stacks_in_1020_page5player = stacks_in_1020_page5elements.stacks_in_1020_page5container.flash().get(0);

			// Creating the control Div. It will act as a ply/pause button

			stacks_in_1020_page5elements.stacks_in_1020_page5control = $('<div>',{className:'stacks_in_1020_page5controlDiv play'})
							   .appendTo(stacks_in_1020_page5elements.stacks_in_1020_page5container);


			// If the user wants to show the progress bar:

			if(settings.progressBar){
				stacks_in_1020_page5elements.progress =	$('<div>',{className:'progressBar'})
									.appendTo(stacks_in_1020_page5elements.stacks_in_1020_page5container);

				stacks_in_1020_page5elements.elapsed =	$('<div>',{className:'elapsed'})
									.appendTo(stacks_in_1020_page5elements.progress);
				
				stacks_in_1020_page5elements.progress.click(function(e){
					
					// When a click occurs on the progress bar, seek to the
					// appropriate moment of the video.
					
					var ratio = (e.pageX-stacks_in_1020_page5elements.progress.offset().left)/stacks_in_1020_page5elements.progress.outerWidth();
					
					stacks_in_1020_page5elements.elapsed.width(ratio*100+'%');
					stacks_in_1020_page5elements.stacks_in_1020_page5player.seekTo(Math.round(data.duration*ratio), true);
					return false;
				});

			}

			var initialized = false;
			
			// Creating a global event listening function for the video
			// (required by YouTube's player API):

			

			
			window['eventListener_'+settings.safeID] = function(status){

				var interval;
				
				if(status==-1)	// video is loaded
				{
					if(!initialized)
					{

				
					// changed to autoplay is selected execute next block by default
					 setTimeout(function(){$('.stacks_in_1020_page5controlDiv.play').eq(0).click();},10);
					 
								
								
						// Listen for a click on the control button:
						stacks_in_1020_page5elements.stacks_in_1020_page5container.click(function(){
							if(!stacks_in_1020_page5elements.stacks_in_1020_page5container.hasClass('playing')){
								
								// If the video is not currently playing, start it:

								stacks_in_1020_page5elements.stacks_in_1020_page5control.removeClass('play replay').addClass('pause');
								stacks_in_1020_page5elements.stacks_in_1020_page5container.addClass('playing');
								stacks_in_1020_page5elements.stacks_in_1020_page5player.playVideo();
								
								if(settings.progressBar){
									interval = window.setInterval(function(){
										stacks_in_1020_page5elements.elapsed.width(
											((stacks_in_1020_page5elements.stacks_in_1020_page5player.getCurrentTime()/data.duration)*100)+'%'
										);
									},1000);
								}
								
							} else {
								
								// If the video is currently playing, pause it:
								
								stacks_in_1020_page5elements.stacks_in_1020_page5control.removeClass('pause').addClass('play');
								stacks_in_1020_page5elements.stacks_in_1020_page5container.removeClass('playing');
								stacks_in_1020_page5elements.stacks_in_1020_page5player.pauseVideo();
								
								if(settings.progressBar){
									window.clearInterval(interval);
								}
							}
						});
						
						initialized = true;
					}
					else{
						// This will happen if the user has clicked on the
						// YouTube logo and has been redirected to youtube.com

						if(stacks_in_1020_page5elements.stacks_in_1020_page5container.hasClass('playing'))
						{
							stacks_in_1020_page5elements.stacks_in_1020_page5control.click();
						}
					}
				}
				
				if(status==0){ // video has ended
					stacks_in_1020_page5elements.stacks_in_1020_page5control.removeClass('pause').addClass('replay');
					stacks_in_1020_page5elements.stacks_in_1020_page5container.removeClass('playing');
				}
			}
			
			
			
			// This global function is called when the player is loaded.
			
			if(!window.onYouTubePlayerReady)
			{				
				window.onYouTubePlayerReady = function(playerID){
					document.getElementById('video_'+playerID).addEventListener('onStateChange','eventListener_'+playerID);
				}
			}
		},'jsonp');

		return stacks_in_1020_page5elements.stacks_in_1020_page5originalDIV;
	}
	
	
	
	
	
	
	//Start My Lightbox jQuery
	
    $.fn.stacks_in_1020_page5_lightbox = function(options) {

        return this.each(function() {

            var
                opts = $.extend({}, $.fn.stacks_in_1020_page5_lightbox.defaults, options),
                $overlay = $('div.lb_overlay'),
                $self = $(this),
                $iframe = $('iframe#lb_iframe'),
                ie6 = ($.browser.msie && $.browser.version < 7);
            
            if ($overlay.length > 0) {
                $overlay[0].removeModal(); // if the overlay exists, then a modal probably exists. Ditch it!
            } else {
                $overlay =  $('<div class="lb_overlay" style="display:none;"/>'); // otherwise just create an all new overlay. 
            }

            $iframe = ($iframe.length > 0) ? $iframe : $iframe = $('<iframe id="lb_iframe" style="z-index: ' + (9999 + 1) + '; display: none; border: none; margin: 0; padding: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0;"/>');

            /*----------------------------------------------------
               DOM Building
            ---------------------------------------------------- */
            if (ie6) {
                var src = /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank';
                $iframe.attr('src', src);
                $('body').append($iframe);
            } // iframe shim for ie6, to hide select elements
            $('body').append($self).append($overlay);

            /*----------------------------------------------------
               CSS stuffs
            ---------------------------------------------------- */

            // set css of the modal'd window

            setSelfPosition();
            $self.css({left: '50%', marginLeft: ($self.outerWidth() / 2) * -1,  zIndex: (9999 + 3) });

            // set css of the overlay

            setOverlayHeight(); // pulled this into a function because it is called on window resize.
            $overlay.css({ position: 'absolute', width: '100%', top: 0, left: 0, right: 0, bottom: 0, zIndex: (9999 + 2) })
                    .css(opts.overlayCSS);
                    
 

            /*----------------------------------------------------
               Animate it in.
            ---------------------------------------------------- */

            if ($overlay.is(":hidden")) {
                $overlay.fadeIn(opts.overlaySpeed, function() {
                    $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); opts.onLoad()});
                });
            } else {
                $self[opts.appearEffect](opts.lightboxSpeed, function() { setOverlayHeight(); opts.onLoad()});
            }

            /*----------------------------------------------------
               Bind Events
            ---------------------------------------------------- */

            $(window).resize(setOverlayHeight)
                     .resize(setSelfPosition)
                     .scroll(setSelfPosition)
                     .keydown(observeEscapePress);
                     
            $self.find(opts.closeSelector).click(function() { removeModal(true); return false; });
            $overlay.click(function() { if(opts.closeClick){ removeModal(true); return false;} });

            
            $self.bind('close', function() { removeModal(true) });
            $self.bind('resize', setSelfPosition);
            $overlay[0].removeModal = removeModal;

            /*----------------------------------------------------------------------------------------------------------------------------------------
              ---------------------------------------------------------------------------------------------------------------------------------------- */

            /*----------------------------------------------------
               Private Functions
            ---------------------------------------------------- */


            function removeModal(removeO) {
                // fades & removes modal, then unbinds events
                $self[opts.disappearEffect](opts.lightboxDisappearSpeed, function() {
                    
                    if (removeO) {
                      removeOverlay();  
                    } 
                    
                    opts.destroyOnClose ? $self.remove() : $self.hide()
                    
                    
                    $self.find(opts.closeSelector).unbind('click');
                    $self.unbind('close');
                    $self.unbind('resize');
                    $(window).unbind('scroll', setSelfPosition);
                    $(window).unbind('resize', setSelfPosition);
                    
                    
                });
            }
            
            
            function removeOverlay() {
                // fades & removes overlay, then unbinds events
                $overlay.fadeOut(opts.overlayDisappearSpeed, function() {
                    $(window).unbind('resize', setOverlayHeight);
                    
                    $(".stacks_in_1020_page5flashContainer").remove();
                    $overlay.remove();
                    $overlay.unbind('click');
                    
                    
                    
                    opts.onClose();

                })
            }


            /* Function to bind to the window to observe the escape key press */
            function observeEscapePress(e) {
                if((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)) && opts.closeEsc) removeModal(true);
            }

            /* Set the height of the overlay
                    : if the document height is taller than the window, then set the overlay height to the document height.
                    : otherwise, just set overlay height: 100%
            */
            function setOverlayHeight() {
                if ($(window).height() < $(document).height()) {
                    $overlay.css({height: $(document).height() + 'px'});
                } else {
                    $overlay.css({height: '100%'});
                    if (ie6) {$('html,body').css('height','100%'); } // ie6 hack for height: 100%; TODO: handle this in IE7
                }
            }

            /* Set the position of the modal'd window ($self)
                    : if $self is taller than the window, then make it absolutely positioned
                    : otherwise fixed
            */
            function setSelfPosition() {
                var s = $self[0].style;

                if (($self.height() + 80  >= $(window).height()) && ($self.css('position') != 'absolute' || ie6)) {
                    var topOffset = $(document).scrollTop() + 40;
                    $self.css({position: 'absolute', top: topOffset + 'px', marginTop: 0})
                    if (ie6) {
                        s.removeExpression('top');
                    }
                } else if ($self.height()+ 80  < $(window).height()) {
                    if (ie6) {
                        s.position = 'absolute';
                        if (opts.centered) {
                            s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')
                            s.marginTop = 0;
                        } else {
                            var top = (opts.modalCSS && opts.modalCSS.top) ? parseInt(opts.modalCSS.top) : 0;
                            s.setExpression('top', '((blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"')
                        }
                    } else {
                        if (opts.centered) {
                            $self.css({position: 'fixed', top: '50%', marginTop: ($self.outerHeight() / 2) * -1}).css({
                            																							borderWidth: "1px", 
                            																							borderStyle: "solid", 
                            																							borderColor: doooverlaycolour
                            																							})
                        } else {
                            $self.css({ position: 'fixed'}).css(opts.modalCSS);
                        }
                    }
                }
            }
        });
    };

	
	
	
	
	
    $.fn.stacks_in_1020_page5_lightbox.defaults = {

        // animation when appears
        appearEffect: "fadeIn",
        overlaySpeed: 2000,
        lightboxSpeed: 2500,
        
        // animation when dissapears
        disappearEffect: "fadeOut",
        overlayDisappearSpeed: 1000,
        lightboxDisappearSpeed: 1000,

        // close
        closeSelector: ".close",
        closeClick: true,
        closeEsc: true,

        // behavior
        destroyOnClose: false,

        // callbacks
        onLoad: function() {},
        onClose: function() {},

        // style
        classPrefix: 'lb',
        zIndex: 9999,
        centered: true,
        modalCSS: {top: '40px'},
        overlayCSS: {background: doooverlaycolour, opacity: doooverlaytransparency}
    }
    
    
    
    
    
    //Start My Video Thumbnail jQuery
    
    // get the thumbnail
    	$.extend({
		jYoutube: function( url, size ){
			if(url === null){ return ""; }

			size = (size === null) ? "big" : size;
			var vid;
			var results;

			results = url.match("[\\?&]v=([^&#]*)");

			vid = ( results === null ) ? url : results[1];

			if(size == "small"){
				return "http://img.youtube.com/vi/"+vid+"/2.jpg";
			}else {
				return "http://img.youtube.com/vi/"+vid+"/0.jpg";
			}
		}
	})
    
    // get the stripped id from the url
    var getid = function(url, gkey){

        var returned = null;

        if (url.indexOf("?") != -1){

          var list = url.split("?")[1].split("&"),
                  gets = [];

          for (var ind in list){
            var kv = list[ind].split("=");
            if (kv.length>0)
                gets[kv[0]] = kv[1];
        }

        returned = gets;

        if (typeof gkey != "undefined")
            if (typeof gets[gkey] != "undefined")
                returned = gets[gkey];

        }

        return returned;

};
	   

})(jQuery);






$('.stacks_in_1020_page5tubeWrapper').each(function() {
var tubeurl = $(".stacks_in_1020_page5Url",this).text();
var thumb = $.jYoutube(tubeurl , 'big');
$(".stacks_in_1020_page5dooTube_ThumbLink",this).append("<img src=' " + thumb + " ' alt='" + tubeurl + "' />");
});


    
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)))
{
$(".stacks_in_1020_page5title").html("Not Available to Play on iPhone, iPod or iPad");
}
else {
 
$('.stacks_in_1020_page5dooTube_ThumbLink').click(function() {
var url = $("img",this).attr("alt");

$('.stacks_in_1020_page5player').stacks_in_1020_page5youTubeEmbed({
	video			: url,
	width			: popupwidth, 		// Height is calculated automatically
	progressBar	: false		// Hide the progress bar
	});

});

}





});

	return stack;
})(stacks.stacks_in_1020_page5);



