var Card = {
	initialize: function(id) {
		this.params = this.base3(id);
	},
	base3: function(num) {
		var digits = [0,0,0,0,0,0];
		var i = 0;
		while (num > 0) {
			digits[i] = num % Math.pow(3,i+1) / Math.pow(3,i);
			num -= num%Math.pow(3,i+1);
			i++;
		}
		return digits;
	},
	flashBorder: function(color,duration) {
		this.style.borderColor = color;
		setTimeout(this.resetBorder.bind(this),duration);
	},
	resetBorder: function() {
		this.style.borderColor = '';
	},
	onclick: function() {
		gameplay.select(this);
	}
}

var gameplay = {
	initialize: function() {
		this.selected = [];
		document.getElementsByClassName('card').each(function(image) {
			if (!image.base3) {
				Object.extend(Element.extend(image),Card).initialize(image.id);
			}
		}.bind(this));
	},
	select: function(card) {
		if (card.hasClassName('selected')) {
			this.selected = this.selected.without(card);
			card.removeClassName('selected');
			card.flashBorder('#fff',700);
		} else {
			this.selected.push(card);
			card.addClassName('selected');
			if (this.selected.length == 3) {
				this.selected.each(function(card) { card.removeClassName('selected'); });
				if (this.checkForSet(this.selected)) {
					this.selected.each(function(card) { card.addClassName('set'); });
					this.respondToSet(this.selected);
				} else {
					this.selected.last().flashBorder('#fff',700);
				}
				this.selected.clear();
			}
		}
	},
	checkForSet: function(cards) {
		var same = 0;
		var diff = 0;
		$R(0,5).each(function(i) {
			if ((cards[0].params[i] == cards[1].params[i]) &&
			 	(cards[0].params[i] == cards[2].params[i])) {
				same++;
			}
			if ((cards[0].params[i] != cards[1].params[i]) && 
				(cards[0].params[i] != cards[2].params[i]) &&
				(cards[1].params[i] != cards[2].params[i])) {
				diff++;
			}
		});
		if (same + diff == 6) return true;
		return false;
	},
	respondToSet: function(set) {
		var options = {
			method: 'post',
			parameters: 'set[0]='+set[0].id+'&set[1]='+set[1].id+'&set[2]='+set[2].id
		};
		new Ajax.Request('welcome/set',options);
	},
	redeal: function() {
		if (stopwatch.running) {
			var options = {
				onComplete: function() { Element.hide('redealing'); }
			};
			Element.show('redealing');
			new Ajax.Request('welcome/redeal',options);
		}
	},
	deal_to_vacant: function() {
		if (stopwatch.running) {
			var vacant_spots = this.vacantSpots();
			if (vacant_spots.length > 0) {
				var options = {
					method: 'post',
					parameters: vacant_spots.inject("",function(s,id,i) { 
						return s + "spots[" + i + "]=" + id + "&";
					}),
					onComplete: function () { Element.hide('filling'); }
				};
				Element.show('filling');
				new Ajax.Request('welcome/deal_to_vacant',options);
			}
		}
	},
	vacantSpots: function() {
		return $A($('card_table').getElementsByTagName('td')).findAll(function(td) {
			return !td.hasChildNodes();
		}).collect(function(td){ return td.id });
	},
	hint: function() {
		if (stopwatch.running) {
			var options = {
				onComplete: function() { Element.hide('hinting'); }
			};
			Element.show('hinting');
			new Ajax.Request('welcome/hint',options);
		}
	},
	pause: function() {
		$A(['about','card_table','read','play']).each(function(el) {
			Element.toggle(el);
		});
		stopwatch.pause();
	}
}		

var stopwatch = {
	running: false,
	timer: null,
	priorSecs: 0,
	start: function() {
		this.startDate = new Date();
		this.startSecs = this.startDate.getHours()*3600 + this.startDate.getMinutes()*60 + this.startDate.getSeconds();
		this.show();
	},
	stop: function() {
		if (this.running) {
			clearTimeout(this.timer);
			this.running = false;
		}
	},
	pause: function() {
		if (this.running) {
			clearTimeout(this.timer);
			this.running = false;
			this.priorSecs = this.elapsedSecs();
		} else {
			this.running = true;
			this.start();
		}
	},
	elapsedSecs: function() {
		var now = new Date();
		var nowSecs = now.getHours()*3600 + now.getMinutes()*60 + now.getSeconds();
		return nowSecs - this.startSecs + this.priorSecs;		
	},
	show: function() {
		var elapsedSecs = this.elapsedSecs();
		var hours = Math.floor(elapsedSecs/3600);
		elapsedSecs = elapsedSecs - hours*3600;
		var minutes = Math.floor(elapsedSecs/60);
		elapsedSecs = elapsedSecs - minutes*60;
		var seconds = elapsedSecs;
		$('stopwatch').innerHTML = hours + (minutes < 10 ? ":0" : ":") + minutes + (seconds < 10 ? ":0" : ":") + seconds;
		this.timer = setTimeout(this.show.bind(this),1000);
		this.running = true;
	}
}		

window.onload = function() {
	gameplay.initialize();
	stopwatch.start();
}
