/*
	Preloader - should Preload another Page? Trying to request the page and its
	assets from PageManager, without inserting until the assets are loaded?
	
	needs a url to Preload, and an animation to display while doing so...
	ex/ new Preloader(url, animation, options)
*/
var Preloader = new Class({
	
	Implements: [Events, Options],
	
	options: {
		delay: 0,
		count: 1
	},
	
	initialize: function(videoSrc, destination, options) {
		this.setOptions(options);
		var video, 
			delay = this.options.delay
			page = PageManager.getPage(destination),
			count = this.options.count,
			currentCount = 0,
			that = this;
		//start preloading Page
		if(!page.isLoaded()) page.load();

		video = this.video = Preloader.getVideo(videoSrc);
		video.play();
		
		this.reset = function () { 
			video.addEvent('ended', handler);
			currentCount = 0;
			
			video.setCurrentTime(0.1);
			video.play();
		};
		
		var handler = function() {
			currentCount++;
			if(currentCount >= count || !video.isVideo())
			{
				
				video.pause();
				if(destination) {
					PageManager.redirect(destination, delay);
				}
				that.fireEvent('done');
				
			}
			else
			{
				video.setCurrentTime(0);
				video.play();
			}
		};
		
		video.addEvent('ended', handler);
		
		PageManager.getCurrentPage().addEvents({
			'insert': function() {
				video.setCurrentTime(0);
				video.play();
			},
			'remove': function() {
				video.pause();
			}
		});
		
	},
	
	toElement: function() {
		return $(this.video);
	}
	
});
Preloader.getVideo = function (videoSrc) {
	if(!Preloader.videos[videoSrc])
	{
		Preloader.videos[videoSrc] = new Video(videoSrc, { controls: null, height: 480, width:864, autoplay: 'autoplay', hasAudio: false });
	}
	return Preloader.videos[videoSrc];
};
Preloader.videos = {};