var PolTunnel = (function () {

	"use strict";

	var _model,
		_duration = 0,
		_sync,
		_width,
		_height,
		_ctx,
		_preflightCallback,
		_pt,
		_s;

	var _bctx,
		_sAlpha,
		_sYoff,
		_sXoff,
		_blackFade,
		_glow;

	function preflight(callbackFn, duration, model) {
		_preflightCallback = callbackFn;

		_duration = duration;
		_model = model;

		_sync = _model.sync;
		_width = _model.width();
		_height = _model.height();

		initSync();

		_ctx = _model.twoDeeRenderer;

		_preflightCallback();

		//barHeight = _height/2.5;
	}

	function init() {
		_model.on("resize", resize);

		Random.seed(42424242, 8000085, 1333337, 4242424);

		_bctx = document.createElement('canvas').getContext('2d');
		_bctx.canvas.width = _width / 2;
		_bctx.canvas.height = _height / 2;

		_pt = new PolyTunnel();
		_pt.setContext(_ctx);
		_pt.setCenter(_width / 2, _height / 3);

		_s = new Starfield();
		_s.setContext(_bctx);
		_s.setCenter(_width / 2, _height / 3);
	}

	function initSync() {
		_blackFade = _sync.getTrack('blackFade');
		_glow = _sync.getTrack('glow');

		_sAlpha = _sync.getTrack('0:sAlpha');
		_sYoff = _sync.getTrack('0:sYOff');
		_sXoff = _sync.getTrack('0:sXOff');
	}

	function render(row, sceneTime, frameDelta) {
		_ctx.fillStyle = '#000000';
		_ctx.fillRect(0, 0, _width, _height);

		var offsetX =  (_width * 0.5) + (_sXoff.getValue(row) / 1920 * _width),
			offsetY = (_height * 0.333) + (_sYoff.getValue(row) / 1080 * _height);

		_ctx.save();
		_pt.setCenter(offsetX, offsetY);
		_pt.render(frameDelta, row);
		_ctx.restore();

		_ctx.save();
		_s.setCenter(offsetX *.5, offsetY *.5);
		_bctx.clearRect(0,0,_width *.5,_height *.5);
		_s.render(frameDelta/100);
		_ctx.globalCompositeOperation = 'color-dodge';
		_ctx.drawImage(_bctx.canvas, 0,0, _width,_height);
		_ctx.restore();

		var glow = _glow.getValue(row),
			bF = _blackFade.getValue(row);

		if (bF > 0) {
			_ctx.fillStyle = "rgba(0,0,0," + bF + ")";
			_ctx.fillRect(0, 0, _width, _height);
		}

		if (glow > 0) {
			var glowScale = 1;

			for (var i = 0; i < 4; i++) {
				glowScale += .01;
				var sW = _width * glowScale,
					sH = _height * glowScale;
				_ctx.save();
				_ctx.globalCompositeOperation = 'lighter';
				_ctx.globalAlpha = glow;
				_ctx.drawImage(_ctx.canvas, (_width - sW) / 2, (_height - sH) / 2, sW, sH);
				_ctx.restore();
			}
		}

		_ctx.drawImage(Meat.vignette, 0, 0, _width, _height);
	}

	function clear() {
		_model.on("resize", function () {
		});
	}

	function resize(width, height) {
		_width = width;
		_height = height;
	}

	return {
		preflight: preflight,
		init: init,
		render: render,
		clear: clear,
		resize: resize
	};
}());