var MagnifyPipeline = { };

MagnifyPipeline.Youtube = { 
	states: {		
		'-1': "unstarted",
		'0': "ended",
		'1': "playing",
		'2': "paused",
		'3': "buffering",
		'5': "cued"
	}
};

MagnifyPipeline.Youtube.Control = Class.create( MagnifyPipeline.Youtube, {
	initialize: function( config ) {
		this.id = config.id;
	},
	
	skip: function() {
		try {
			if ( typeof(loadNext) == 'function' ) {
				setTimeout(loadNext, 1000);
			}
		} catch(e) { 
			return;
		}
	},
	
	loadNext: function(state) {	
		try {
			if ( ( state == 0 ) && ( typeof(loadNext) == 'function' ) ) {
				loadNext();
			} else {
				return;
			}
		} catch(e) {
			return;
		}
	}
});


MagnifyPipeline.Youtube.Track = Class.create( MagnifyPipeline.Youtube, {
	initialize: function(config) {
		this.id = config.id;
		var stats = new MagnifyStats.Video( config );
		stats.registerTracker( this );
		this.stats = stats;
		this.lastState = -1;
		this.currentState = -1;
		this.currentOffset = 0;
		this.lastOffset = 0;
	},
								
	trackPlayer: function( player ) {
		this.stats.registerPlayer( player );
		this.player = player;
	},
	
	monitorStateChange: function( state ) {
		var tracking = this;
		var evt = MagnifyPipeline.Youtube.states[state];
		
		
		this.lastState = this.currentState;
		this.currentState = state;
		
		var offset = Math.round( this.player.getCurrentTime() );
		this.lastOffset = this.currentOffset;
		this.currentOffset = offset;
		
		if ( this.lastState < 0 ) {
			tracking.startTracking( this.player, evt, offset );
		}
		this.stats.debug("youtube state is: " + state + ", my state is " + this.stats.state);
		//this.stats.debug("last offset: " + this.lastOffset + ", current offset: " + this.currentOffset);
		switch(state) {
			case 0:
				if ( this.lastOffset != this.currentOffset ) {
					this.stats.debug("I'm stopping at " + offset);
					tracking.stopTracking(this.player, evt);
				}
			
			case 1:
				if ( this.lastState != this.currentState ) {
					this.stats.debug("I'm resuming at " + offset);
					tracking.resumeTracking(evt, offset);
				}
				
			case 2:
				if ( this.lastOffset != this.currentOffset ) {
					this.stats.debug("I'm pausing at " + offset);
					tracking.pauseTracking(evt, offset);
				}			
		}
	},
	
	startTracking: function(player, evtType, offset) {	
		var clipId = this.id;
		this.stats.startLogging({ cid: clipId, p: 'youtube' }, Math.round( offset ));
	},
	
	pauseTracking: function(evtType, offset) {
		//this.stats.debug("something told me to pause.");
		this.stats.log("e", evtType, Math.round( offset ));
	},
	
	resumeTracking: function(evtType, offset) {
		this.stats.log("s", evtType, Math.round( offset ));
	},
	
	stopTracking: function(player, evtType, offset) {
		var offset = player.getCurrentTime();
		this.stats.stopLogging(Math.round( offset ));
	},
	
	getPlayerOffset: function() {
		if ( this.player ) 
			return this.player.getCurrentTime();
	}
});