Gimme.Widgets = Gimme.Widgets || {};
Gimme.Widgets.PhotoAlbums = {};

(function()
{
	g(window)
	.addEvent('load', initPhotoAlbums)
	.addEvent('load', initPhotoAlbumWidgets);
	
	function initPhotoAlbumWidgets(e)
	{
		var baseUrl = './wp-content/plugins/spacesphotoalbum/getphotos.php?url=http://stchur.spaces.live.com/photos/';
		g('.spacesPhotoAlbum-widget').forEach(function(_elem, _i)
		{
			var guid = _elem.id;
			_elem.id = 'theAlbum';
			var theAlbum = Gimme.Widgets.createPhotoAlbum(_elem);
			theAlbum.configure({imageHeight:150});
			loadAlbum(guid);
			
			var albumSelector = Gimme.id('albumSelector');
			
			g(albumSelector).addEvent('change', function()
			{
				loadAlbum(this.options[this.selectedIndex].value);
			});
			
			theAlbum.addTrigger('looparound', function()
			{
				theAlbum.pause();
				var ops = albumSelector.options;
				var idx = albumSelector.selectedIndex + 1;
				if (idx > ops.length - 1)
				{
					idx = 0;
				}
				loadAlbum(ops[idx].value);
				albumSelector.selectedIndex = idx;
				return false;
			});			
			
			function loadAlbum(_guid)
			{
				theAlbum.pause();
				var url = baseUrl + _guid + '/feed.rss';
			    theAlbum.loadFromFeed(url, null, theAlbum.play);
			}
			
			g('.spacesPhotoAlbum').addEvent('click', albumWidgetClick);
			function albumWidgetClick(e)
			{
			    var idx = theAlbum.index;
			    theAlbum.pause();
			    var clone = this.cloneNode(true);
			    clone.id = 'clonedAlbum';
			    clone.style.top = '-1000px';
			    clone.style.left = '50%';
			    clone.style.position = 'absolute';
			    clone.style.visibility = 'hidden';
			    g(clone).removeClass('spacesPhotoAlbum-widget');
			    document.body.appendChild(clone);
			    clone.style.marginLeft = -clone.offsetWidth / 2 + 'px';
			    var bigAlbum = Gimme.Widgets.createPhotoAlbum(clone);
			    bigAlbum.configure({imageHeight:300});
			    bigAlbum.loadFromFeed(baseUrl + albumSelector.options[albumSelector.selectedIndex].value + '/feed.rss', 1,
			    function()
			    {
			        bigAlbum.loadImage(idx);
			        clone.style.visibility = 'visible';
			        clone.style.zIndex = '9999';
			        g(clone).slideToPoint({ x: null, y: 100 }, 'slowly');

			        g(mask).addEvent('click', function(e)
			        {
			            g(this).removeEvent('click', arguments.callee);
			            g(clone).slideToPoint({ x: null, y: -1000 }, 'slowly');
			            document.body.removeChild(mask);
			            Gimme.Widgets.PhotoAlbums['theAlbum'].play();
			        });
			    });
			    var mask = document.createElement('div');
			    mask.className = 'spacesPhotoAlbumMask';
			    document.body.appendChild(mask);
			}			
		});
	}
	
	function initPhotoAlbums()
	{
		g('.spacesPhotoAlbum').forEach(function(_el, _i)
		{
			var album = Gimme.Widgets.PhotoAlbums['album_' + _i] = Gimme.Widgets.createPhotoAlbum(_el);
			album.configure({imageHeight:200});
			album.loadFromFeed('./wp-content/plugins/spacesphotoalbum/getphotos.php?url=' + album.config.feed, .2, album.play);
		});
	}
		
	Gimme.Widgets.createPhotoAlbum = function(_elem)
	{
		return Gimme.Widgets.PhotoAlbums[_elem.id] = new PhotoAlbum(_elem);
	};
	function PhotoAlbum(_elem)
	{
		var me = this;
		this.elem = _elem;
		this.title = g(_elem).select('.title').element();
		this.photoHolder = g(_elem).select('.photo').element();
		this.caption = g(_elem).select('.caption').element();
		this.thumbnails = g(_elem).select('.thumbnails').element();
		
		this.triggers = {};
		this.index = null;
		this.iid = null;
		this.buffering = null;
		
		this.config =
		{
			feed: eval('(' + g(_elem).select('.config').getHTML().replace(/&amp;/, '&') + ')').feed,
			albumSize: { width: null, height: null },
			imageSize: { width: null, height: null }
		};
		
		// events
		g(_elem).select('.next').addEvent('click', next);
		g(_elem).select('.prev').addEvent('click', prev);
		g(_elem).select('.play_pause').addEvent('click', play);
		
		function next()
		{
			pause.call(g('.play_pause').element());
			me.next();
		}
		function prev()
		{
			pause.call(g('.play_pause').element());
			me.prev();
		}
		function play()
		{
			g(this).addClass('playing');
			me.play();
			g(this).removeEvent('click', play);
			g(this).addEvent('click', pause);
		}
		function pause()
		{
			g(this).removeClass('playing');
			me.pause();
			g(this).removeEvent('click', pause);
			g(this).addEvent('click', play);
		}
	};
	PhotoAlbum.prototype.configure = function(_ops)
	{
		this.config.albumSize.width = _ops.albumWidth;
		this.config.albumSize.height = _ops.albumHeight;
		this.config.imageSize.width = _ops.imageWidth;
		this.config.imageSize.height = _ops.imageHeight;
		
		//g(this.elem).setStyles(
		//	'height', this.config.albumSize.height + 'px',
		//	'width', this.config.albumSize.width + 'px');
	}
	PhotoAlbum.prototype.loadFromFeed = function(_feed, _pctBuffer, _callback)
	{
		var me = this;
		Gimme.AJAX.requestJSON(_feed, init);
		function init(_json)
		{
			me.loadFromJSON(_json, _pctBuffer, _callback);
			me = null;
		}
	};
	PhotoAlbum.prototype.loadFromJSON = function(_data, _pctBuffer, _callback)
	{
		// defaults
		_pctBuffer = _pctBuffer || .5;
		
		var me = this;
		
		this.index = 0;
		this.buffering = true;
		this.data = _data.imageData;
		this.title.innerHTML = _data.title;
		this.photoHolder.innerHTML = 'Loading album...';
		var img, thumbnail;
		var i, len = this.data.length;
		for (i = 0; i < len; i++)
		{
			img = document.createElement('img');
			g(img).addEvent('load', imageLoaded);
			thumbnail = document.createElement('img');
			img.src = this.data[i].src.replace(/:thumbnail/i, '');
			thumbnail.src = this.data[i].src;
			thumbnail.setAttribute('height', '40');
			this.data[i].img = img;
			this.thumbnails.appendChild(thumbnail);
		}
		
		var complete = 0;
		function imageLoaded(e)
		{
			complete++;
			if (me.buffering && complete / len >= _pctBuffer)
			{
				me.buffering = false;
				me.loadImage(me.index);
				_callback && _callback.call(me);
			}
			
			if (complete === len)
			{
				me = null;
			}
		}		
	};
	PhotoAlbum.prototype.next = function()
	{
		if (this.buffering)
		{
			return;
		}
		this.loadImage(this.index + 1);
	};
	PhotoAlbum.prototype.prev = function()
	{
		if (this.buffering)
		{
			return;
		}
		this.loadImage(this.index - 1);
	};
	PhotoAlbum.prototype.play = function()
	{
		this.pause();
		var me = this.me = this;	
		this.iid = setInterval(function() { me.next(); }, 2500);
	};
	PhotoAlbum.prototype.pause = function()
	{
		this.me = null;
		clearTimeout(this.iid);
	};
	PhotoAlbum.prototype.loadImage = function(_idx)
	{
		if (_idx > this.data.length - 1)
		{
			_idx = 0;
			if (this.pullTrigger('looparound') === false)
			{
				return;
			}
		}
		else if (_idx < 0)
		{
			_idx = this.data.length - 1;
		}
		
		var currentImage = this.photoHolder.firstChild;
		var newData = this.data[_idx];
		if (newData)
		{
			if (currentImage)
			{
				currentImage.parentNode.removeChild(currentImage);
			}
			
			this.photoHolder.appendChild(newData.img);
			var h = newData.img.height;
			var w = newData.img.width;
			newData.img.style.height = this.config.imageSize.height + 'px';
			newData.img.style.width = this.config.imageSize.height * w / h + 'px';
			this.index = _idx;
			g(newData.img).setStyle('opacity', '0').fadeIn();
			g(this.caption).setHTML(newData.title);
			currentImage = null;
		}
	};
	PhotoAlbum.prototype.showThumbnails = function()
	{
		var me = this;
		g(this.thumbnails).slideToPoint({x: 0, y: null }, null, 'THUMBNAIL_SLIDE', null, Gimme.Animation.AccelerationLines.quickStartDecelerate);
		
		g(this.elem).select('.thumbnails img').iterate(function(i)
		{
			this.addEvent('click', thumbnailClick(i));
		});
		
		function thumbnailClick(idx)
		{
			return function()
			{
				me.loadImage(idx);
			}
		}
	};
	PhotoAlbum.prototype.addTrigger = function(_type, _fn)
	{
		var t = this.triggers[_type];
		if (!t)
		{
			t = this.triggers[_type] = [];
		}
		t.push(_fn);
	};
	PhotoAlbum.prototype.removeTrigger = function(_type, _fn)
	{
		var idx;
		var t = this.triggers[_type];
		if (t)
		{
			idx = g(t).indexOf(_fn);
			if (idx !== -1)
			{
				this.triggers.splice(idx, 1);
			}
		}
	};
	PhotoAlbum.prototype.pullTrigger = function(_type)
	{
		var result = true;
		var i, len;
		var t = this.triggers[_type];
		if (t)
		{
			len = t.length;
			for (i = 0; i < len; i++)
			{
				if (!t[i].call())
				{
					result = false;
				}
			}
		}
		return result;
	};
})();