/**
 * Map
 */
function MapModel() {
	this.cells = $('.map .cell');
}

MapModel.prototype = {
	getRandomFlipCell: function () {
		var num = Math.floor(Math.random() * 4 + 1);
		var ret = [];
		for (var i = 0; i < num; i++) {
			ret.push({
				from: Math.floor(Math.random() * this.cells.length),
				to:   Math.floor(Math.random() * 20 + 1)
			});
		}
		return ret;
	}
};

function MapView() {
	
}

MapView.prototype = {
	flip: function (cellId, episodeId) {
		var self = this;
		var cell = $('#cell' + cellId);
		var before = cell.html();
		var after = before.replace(/id=[0-9]+/, 'id=' + episodeId).replace(/thumb_[0-9]+/, 'thumb_' + MapUtil.strPad(episodeId, 5, '0'));
		cell.flip({
			content: after,
			bgColor: '#FEF4DA',
			color: '#FEF4DA',
			speed: 350,
			onEnd: function () {
				if (typeof self.delegate.flipEnd === 'function') 
					self.delegate.flipEnd(cellId, episodeId);
			}
		});
	}
};

function MapController(model, view) {
	this.model = model;
	this.view = view;
	this.view.delegate = this;
	this.init();
}

MapController.prototype = {
	init: function () {
		var self = this;
		setInterval(function () {
			var cells = self.model.getRandomFlipCell();
			for (var i = 0, j = cells.length; i < j; i++) {
				self.view.flip(cells[i].from, cells[i].to);
			}
		}, 4000);
	},
	flipEnd: function () {
	}
};

var MapUtil = {};
MapUtil.strPad = function (str, len, pad) {
	str = str + '';
	len = len - 0;
	pad = pad + '';
	while (str.length < len) {
		str = pad + str;
	}
	return str;
};

