/**
 * Created by admin on 15-5-19.
 */
/**
 * Created by admin on 15-5-12.
 */


(function () {
	var lastTime = 0;
	var vendors = ['ms', 'moz', 'webkit', 'o'];
	for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
		window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
		window.cancelAnimationFrame =
			window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
	}

	var blacklisted = /iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent);

	if (!window.requestAnimationFrame || blacklisted) {
		window.requestAnimationFrame = function (callback, element) {
			var currTime = new Date().getTime();
			var timeToCall = Math.max(0, 16 - (currTime - lastTime));
			var id = window.setTimeout(function () {
					callback(currTime + timeToCall);
				},
				timeToCall);
			lastTime = currTime + timeToCall;
			return id;
		};
	}


	if (!window.cancelAnimationFrame || blacklisted) {
		window.cancelAnimationFrame = function (id) {
			clearTimeout(id);
		};
	}

}());

(function(window){
	var Query = (function (queryString) {

		function parseURL(url) {
			var a =  document.createElement('a');
			a.href = url;
			return {
				source: url,
				protocol: a.protocol.replace(':',''),
				host: a.hostname,
				port: a.port,
				query: a.search,
				params: (function(){
					var ret = {},
						seg = a.search.replace(/^\?/,'').split('&'),
						len = seg.length, i = 0, s;
					for (;i<len;i++) {
						if (!seg[i]) { continue; }
						s = seg[i].split('=');
						ret[s[0]] = s[1];
					}
					return ret;
				})(),
				file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
				hash: a.hash.replace('#',''),
				path: a.pathname.replace(/^([^\/])/,'/$1'),
				relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
				segments: a.pathname.replace(/^\//,'').split('/')
			};
		};

		function hasParam(a){
			var params = parseURL(queryString).params;

			return (a in params);
		};

		function getParamVal(key){
			var params = parseURL(queryString).params;

			return params[key];
		};

		function getHash(){
			return parseURL(queryString).hash;
		};

		// public api
		return {
			hasParam: hasParam,
			getParamVal: getParamVal,
			hash: getHash
		};
	})();

	window.Query = Query;
})(window);

window.onload = function () {

	this.canvas = document.querySelector("canvas");
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	this.ctx = canvas.getContext("2d");

	if(this.Game == undefined) this.Game = {};
	Game.slideRatio = 10;
	Game.targetRatio = 10;
	Game.frameRate = 16;
	Game.points = [];

	Game.CurrTrack = NIxiang;

	var Tracks = Game.CurrTrack;

	for (var i = 0, len = Tracks.length; i < len; i++) {

		if (Tracks[i].type == LINE_TYPE.LINE) {
			Game.points = Game.points.concat(Game.getLinePointsByLen(Tracks[i].value, 1));
		}

		if (Tracks[i].type == LINE_TYPE.ARC) {
			Game.points = Game.points.concat(Game.getArcPointsByLen(Tracks[i].value, 1));
		}
	}


	var car = new Car();

	function loop() {
		ctx.clearRect(-1000, -1000, 3000, 3000);

		drawRunway(Game.CurrTrack);

		car.update();
		car.render();

		centerMe(car);

		setTimeout(loop, Game.frameRate);

//		requestAnimationFrame(loop);
	}

	loop();


	//以下，UI操作.
	var $toward = document.querySelector("#vt");
	$toward.addEventListener("change", function (e) {
		e.stopPropagation();
		car.v = Math.floor(Game.RangeMap([1,10],[0,100], Math.abs($toward.value)));
	}, false);

	var $target = document.querySelector("#vg");
	$target.addEventListener("change", function (e) {
		e.stopPropagation();

		//目前，索引值.
		Game.targetRatio = Math.floor(Game.RangeMap([10,200],[0,100], Math.abs($target.value)));
	}, false);


	var $slide = document.querySelector("#vs");
	$slide.addEventListener("change", function (e) {
		e.stopPropagation();

		Game.slideRatio = Game.RangeMap([10,100],[0,100], Math.abs($slide.value));
	}, false);

	var $frame = document.querySelector("#vf");
	$frame.addEventListener("change", function (e) {
		e.stopPropagation();

		Game.frameRate = Game.RangeMap([16,3000],[0,100], Math.abs($frame.value));
	}, false);



	var $canvas = document.querySelector("canvas");

	var isMove = false;
	$canvas.addEventListener("mousedown", function (e) {
		e.stopPropagation();

		var x = e.pageX - $canvas.offsetLeft;
		var y = e.pageY - $canvas.offsetTop;

		isMove = false;

		Line.push([
			{x: x, y: y}
		]);
	}, false);

	$canvas.addEventListener("mousemove", function (e) {
		e.stopPropagation();

		isMove = true;
	}, false);

	$canvas.addEventListener("mouseup", function (e) {
		if (!isMove) {
			Line.pop();
			return;
		}
		var x = e.pageX - $canvas.offsetLeft;
		var y = e.pageY - $canvas.offsetTop;

		Line[Line.length - 1].push({x: x, y: y});
	}, false);
}