/*jslint white: false, plusplus: false, nomen: false */ 
/*global window alert document YUI console Image */


/*!
 * @file logan.js
 * @author David Miller dave@readmeansrun.com
 *
 * Built on top of YUI 3 (http://developer.yahoo.com/yui/3/)
 */

var Logan = (function (){

	// regular expression for parsing URL from CSS background image style, ex: "url(http://url-goes-here)"
	var bg = /^\s*url\((.*)\)$/;

	return {

		Y : null, // reference to YUI post-loaded YUI object
		_autoplay : false, 
		_slides : {
			count : 0, 
			urls : {},
			loaded : 0,

			callback : function () {

				// "this" is scoped to the image that just loaded
				var L = Logan, Y = L.Y, gallery = null, divs = null;
				L._slides.loaded++;
				if (L._slides.loaded !== L._slides.count) {
					return; // not ready yet
				}

				gallery = Y.one('#lgn-gallery');
				divs = gallery.all('div');

				divs.item(0).addClass('active');

				new Y.Anim({
					node : gallery,
					to : {
						opacity : 1
					},
					duration : 0.5,
					easing: Y.Easing.easeIn
				}).run();

				if (divs.size() !== 1) {
					divs.item(1).addClass('next');
					Y.later(3000, null, function() {
						var n = Y.one('#lgn-gallery .active'),
						anim = new Y.Anim({
							node : n,
							to : { opacity: 0 },
							duration : 1
						});
						anim.on('end', Logan.rotate);
						anim.run();
					}, null, true);
				}
			}
		}, // keep track of background images 

		init : function(autoplay) {
			this._autoplay = autoplay;
		},

		hasVideo : function() {
			return !!document.createElement('video').canPlayType;
		},


		/* cycle through the images in the stills or gallery containers */
		rotate : function() {

			// "this" is scoped to the animation object

			var i = 0, n = this.get('node'), active = null, next = null, entries = null, e = null;

			n.removeClass('active');
			n.setStyle('display', 'none');
			active = n.next('div');
			if (! active) { active = n.get('parentNode').one('div'); }
			next = active.next('div');
			if (! next) { next = n.get('parentNode').one('div'); }

			entries = n.get('parentNode').all('div');
			for (i = 0; i < n.size(entries); i++) {
				e = entries.item(i);
				if (e !== active && e !== next) { e.setStyle('display', 'none'); }
			}

			active.removeClass('next').addClass('active').setStyle('opacity', 1).setStyle('display', 'block');
			next.addClass('next').setStyle('opacity', 1).setStyle('display', 'block');
		},

		loadSlide : function(div) {

			try { // if there is no bg image

				var src = bg.exec(div.getStyle('backgroundImage'))[1], img = null;

				this._slides.count++;
				this._slides.urls[div.get('className')] = src;

				img = new Image();
				img.onload = Logan._slides.callback; 
				img.src = src.replace('"', '').replace('"', '');
			} catch (e) { }
		},

		play : function(link) {

			var Y = this.Y, a = null, markup = null, vid = null, so = null;

			// if we're in a mobile browser, don't over-ride the click
			if (Y.UA.mobile) { return false; }

			a = link.ancestor('a', true);
			markup = '<div id="lgn-video"><em class="close"></em><video width="720" height="405" controls autoplay>' +
				'<source src="' + a.get('href') + '" type="video/mp4">' +
				'<source src="' + a.get('href').replace('.mp4', '.ogv') + '" type="video/ogg">' +
				'<div id="lgn-swf"></div>' + 
				'</video></div>';

			vid = Y.Node.create(markup);
			Y.one('#doc').prepend(vid);

            var so = new Y.SWF('#lgn-swf', 'assets/swf/flowplayer-3.2.5.swf', {
                version: '9.0.0',
                fixedAttributes : {
                    'wmode' : 'transparent',
                },
                flashVars : {
                    'autoBuffering' : 'true',
                    'autoPlay' : 'true',
                    'config' : '{\'clip\' : \'' + link.get('href') + '\'}',
                }
            });

			if (Y.one('#doc').hasClass('video')) {
				try { // for firefox
					Y.one('video')._node.addEventListener('ended', function(e) { Logan.remove(); });
				} catch (ex) { }
			}

			vid.one('em').on('click', function(e) { e.halt(); Logan.remove(); });
			a = new Y.Anim({
				'node' : Y.one('#lgn-video'),
				to : { opacity: 1 },
				duration : 0.2
			});
			a.on('end', function() { Y.later(100, null, function() { var v = Y.one('video'); if (v) { v._node.play(); } }, null, false); });
			a.run();

			return true;
		},

		slideshow : function() {

			var Y = this.Y, stills = Y.one('#lgn-stills'), a = null;
			stills.addClass('init');

			a = new Y.Anim({
				'node' : stills,
				to : { opacity: 1 },
				duration : 0.2
			});

			if (Y.all('#lgn-stills div').size() > 1) {
				a.on('end', function() {
					Logan.stills = Y.later(5000, null, function() {
						var n = Y.one('#lgn-stills .active'),
						anim = new Y.Anim({
							node : n,
							to : { opacity: 0 },
							duration : 1
						});
						anim.on('end', Logan.rotate);
						anim.run();
					}, null, true);
				});
			}
			a.run();
		},



		remove : function() {

			var Y = this.Y, m = Y.one('#lgn-more'), n = Y.one('#lgn-video'), a = null;

			if (n) {
				a = new Y.Anim({
					'node' : n,
					'to' : { opacity : 0 },
					'duration' : 0.3
				});
				a.on('end', function() { this.get('node').remove(); });
				a.run();

				return;
			}

			n = Y.one('#lgn-stills');
			if (n) { 
				 a = new Y.Anim({
					'node' : n,
					to : { opacity: 0 },
					duration : 0.2
				});

				if (Logan.stills) {
					Logan.stills.cancel();
					Logan.stills = null;
				}
			}

			a.on('end', function() { n.removeClass('init'); });
			a.run();
		}
	};
}());

YUI().use('node', 'anim', 'swf', 'event-key', function(Y) {

		Logan.Y = Y;
		var em = null, divs = null, toggleMore = null, gallery = null, i = 0, v = Y.all('#lgn-play a.video');

		Y.one('#lgn-pages li.directors a').on('click', function(e) {
			e.preventDefault();
			var n = e.target.ancestor('a', true);
			window.open(n.get('href'));
		});

		if (Logan._autoplay) {
			if (v) {
				Logan.play(v.item(0));
			} else if (Y.one('#lgn-stills')) {
				Logan.slideshow();
			}
		}

		Y.on('key', function() { Logan.remove(); }, document.body, 'down:27');

		toggleMore = function(e) {
			e.halt();
			var m = Y.one('#lgn-more'), a = new Y.Anim({
				'node' : m,
				'to' : { opacity : m.hasClass('on') ? 0 : 1 },
				'duration' : 0.1
			});
			a.on('end', function() { this.get('node').toggleClass('on') });
			a.run();
		};

		if (Y.one('#lgn-more')) { 
			Y.one('#lgn-meta .more a').on('click', toggleMore);
			Y.one('#lgn-more em.close').on('click', toggleMore);
		}


		gallery = Y.one('#lgn-gallery');
		if (gallery) { 
			/* rotate through the images in the gallery */
			divs = Y.all('#lgn-gallery div');

			for (i = 0; i < divs.size(); i++) {
				Logan.loadSlide(divs.item(i));
			}
/*
			if (divs.size() != 1) {
				divs.item(0).addClass('active');
				divs.item(1).addClass('next');
				Y.later(3000, null, function() {
					var n = Y.one('#lgn-gallery .active'),
					anim = new Y.Anim({
						node : n,
						to : { opacity: 0 },
						duration : 1
					});
					anim.on('end', rotate);
					anim.run();
				}, null, true);
			}
*/
		}

		Y.all('#lgn-play a').on('click', function(e) {

		    e.halt();
			if (e.target.hasClass('video')) {
			    Logan.play(e.target)
			} else {
			    window.open(e.target.get('href'));
			}
		});



		/* */
		em = Y.one('#lgn-stills em');
		if (em) {
			em.on('click', function(e) { e.halt(); Logan.remove(); });

//			Y.all('a.stills').on('click', function() { e.halt(); Logan.slideshow(); });
		}

/*		toggleMore = function(e) {
			e.halt();
			var m = Y.one('#lgn-more'), a = new Y.Anim({
				'node' : m,
				'to' : { opacity : m.hasClass('on') ? 0 : 1 },
				'duration' : 0.1
			});
			a.on('end', function() { this.get('node').toggleClass('on'); });
			a.run();
		};

		if (Y.one('#lgn-more')) { 
			Y.one('#lgn-meta .more a').on('click', toggleMore);
			Y.one('#lgn-more em.close').on('click', toggleMore);
		}
*/
});
