var score_url = 'http://www.haengematte.net/ecml/memory-flags/scores.php';

var scores_enabled = true; // true or false, no quotes



var img_folder = ''; // example: 'images/'. Leave empty if images are in

                     // the same folder as everything else.

var back = img_folder + 'memory-back.gif';



// Each card img in tiles1 should correspond to the matching card in tiles2

// They should always have the same number of images.

// If you change the number of items in these, change the grid_width and 

// grid_height too.

var tiles1 = [ 'albania.gif', 'andorra.gif', 'armenia.gif', 'austria.gif', 	'bosnia.gif', 'bulgaria.gif', 'COE.gif', 

	'croatia.gif', 'cyprus.gif', 'czech.gif', 'estonia.gif', 'finland.gif', 'france.gif', 'GB.gif',

	'germany.gif', 'greece.gif', 'hungary.gif', 'iceland.gif', 'ireland.gif', 'latvia.gif', 'liechtenstein.gif', 

	'lithuania.gif', 'lux.gif', 'mace.gif',	'malta.gif', 'monte.gif', 'nl.gif', 'norway.gif', 'poland.gif', 

	'romania.gif', 'slovak.gif', 'slovenia.gif', 'spain.gif', 'sweden.gif', 'swiss.gif' ];

var tiles2 = [ 'albania-c.gif', 'andorra-c.gif', 'armenia-c.gif', 'austria-c.gif',

	'bosnia-c.gif', 'bulgaria-c.gif', 'COE-c.gif', 'croatia-c.gif', 'cyprus-c.gif',

	'czech-c.gif', 'estonia-c.gif', 'finland-c.gif', 'france-c.gif', 'GB-c.gif',

	'germany-c.gif', 'greece-c.gif', 'hungary-c.gif', 'iceland-c.gif', 'ireland-c.gif',

	'latvia-c.gif', 'liechtenstein-c.gif', 'lithuania-c.gif', 'lux-c.gif', 'mace-c.gif',

	'malta-c.gif', 'monte-c.gif', 'nl-c.gif', 'norway-c.gif', 'poland-c.gif', 'romania-c.gif',

	'slovak-c.gif', 'slovenia-c.gif', 'spain-c.gif', 'sweden-c.gif', 'swiss-c.gif' ];



// The information to show when a match is made. Should be the same number

// of items as half the tiles.  Can contain HTML

var info = [

'You found:<br><span style="font-size:larger; "><strong>Albania</strong></span><br>(Member)<br>Capital: Tirana<br>Accession: 1995',

'You found:<br><span style="font-size:larger; "><strong>Andorra</strong></span><br>(Member)<br>Capital: Andorra la Vella<br>Accession: 1965',

'You found:<br><span style="font-size:larger; "><strong>Armenia</strong></span><br>(Member)<br>Capital: Yerevan<br>Accession: 2001',

'You found:<br><span style="font-size:larger; "><strong>Austria</strong></span><br>(Member)<br>Capital: Vienna<br>Accession: 1956',

'You found:<br><span style="font-size:larger; "><strong>Bosnia and Herzegowina</strong></span><br>(Member)<br>Capital: Sarajevo<br>Accession: 2002',

'You found:<br><span style="font-size:larger; "><strong>Bulgaria</strong></span><br>(Member)<br>Capital: Sofia<br>Accession: 1992',

'You found:<br><span style="font-size:larger; ">the <strong>COE</strong></span><br>(Member)<br>Capital: Strasbourg',

'You found:<br><span style="font-size:larger; "><strong>Croatia</strong></span><br>(Member)<br>Capital: Zagreb<br>Accession: 1996',

'You found:<br><span style="font-size:larger; "><strong>Cyprus</strong></span><br>(Member)<br>Capital: Nicosia<br>Accession: 1961',

'You found:<br><span style="font-size:larger; "><strong>the Czech Republic</strong></span><br>(Member)<br>Capital: Prague<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>Estonia</strong></span><br>(Member)<br>Capital: Tallinn<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>Finland</strong></span><br>(Member)<br>Capital: Helsinki<br>Accession: 1989',

'You found:<br><span style="font-size:larger; "><strong>France</strong></span><br>(Founding member)<br>Capital: Paris<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>the United Kingdom</strong></span><br>(Founding member)<br>Capital: London<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Germany</strong></span><br>(Member)<br>Capital: Berlin<br>Accession: 1950',

'You found:<br><span style="font-size:larger; "><strong>Greece</strong></span><br>(Member)<br>Capital: Athens<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Hungary</strong></span><br>(Member)<br>Capital: Budapest<br>Accession: 1990',

'You found:<br><span style="font-size:larger; "><strong>Iceland</strong></span><br>(Member)<br>Capital: Reykjavík<br>Accession: 1950',

'You found:<br><span style="font-size:larger; "><strong>Ireland</strong></span><br>(Founding member)<br>Capital: Dublin<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Latvia</strong></span><br>(Member)<br>Capital: Riga<br>Accession: 1995',

'You found:<br><span style="font-size:larger; "><strong>Liechtenstein</strong></span><br>(Member)<br>Capital: Vaduz<br>Accession: 1978',

'You found:<br><span style="font-size:larger; "><strong>Lithuania</strong></span><br>(Member)<br>Capital: Vilnius<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>Luxembourg</strong></span><br>(Founding member)<br>Capital: Luxembourg<br>Accession: 1949',

'You found:<br><span style="font-size:larger; ">the <strong>F.Y.R. Macedonia</strong></span><br>(Member)<br>Capital: Skopje<br>Accession: 1995',

'You found:<br><span style="font-size:larger; "><strong>Malta</strong></span><br>(Member)<br>Capital: Valletta<br>Accession: 1965',

'You found:<br><span style="font-size:larger; "><strong>Montenegro</strong></span><br>(Member)<br>Capital: Podgorica<br>Accession: 2007',

'You found:<br><span style="font-size:larger; ">the <strong>Netherlands</strong></span><br>(Founding member)<br>Capital: Amsterdam<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Norway</strong></span><br>(Founding member)<br>Capital: Oslo<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Poland</strong></span><br>(Member)<br>Capital: Warsaw<br>Accession: 1991',

'You found:<br><span style="font-size:larger; "><strong>Romania</strong></span><br>(Member)<br>Capital: Bucharest<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>the Slovak Republic</strong></span><br>(Member)<br>Capital: Bratislava<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>Slovenia</strong></span><br>(Member)<br>Capital: Ljubljana<br>Accession: 1993',

'You found:<br><span style="font-size:larger; "><strong>Spain</strong></span><br>(Member)<br>Capital: Madrid<br>Accession: 1977',

'You found:<br><span style="font-size:larger; "><strong>Sweden</strong></span><br>(Founding member)<br>Capital: Stockholm<br>Accession: 1949',

'You found:<br><span style="font-size:larger; "><strong>Switzerland</strong></span><br>(Member)<br>Capital: Berne<br>Accession: 1963'

];
var info_enabled = true;

var info_timeout = 0; // Number of seconds. Set to 0 to disable.



// grid_width * grid_height should equal the total number of images (tiles1 and tiles2).

var grid_width = 7;

var grid_height = 10;



/*------------------------------------------*/

/*        NO FURTHER EDITING iS NEEDED      */

/*------------------------------------------*/



var timer_card; // timer id for the cards being shown

var timer_game; // timer id for the whole game

var num_seconds = 0; // num seconds.



var num_moves = 0;



// The hash IDs of the cards currently showing. This doesn't included ones

// you already matched.  So this only contains 0-2 card keys.

var cards_showing = [];

// These are the ones already matched.

var cards_matched = [];



// This is a hash of hashes.

// The key of each element corresponds to the div id of the card.

// The contents of the hash element is a hash with these keys/values:

//        card_number - this is where the card's image was within the original

//                      tiles1 or tiles2 stack. It's just to identify whether

//                      2 images match. So there are 2 cards with each card_number

//        img_src - the 'src' property of the image file.

var deck = new Hash();



var scoreFormSlider;

var playAgainSlider;



// This function gets called as soon as the DOM is ready

window.addEvent('domready', function() {

	if (tiles1.length != tiles2.length) {

		alert("Bad number of tiles");

		return;

	}

	if (grid_width * grid_height != 2 * tiles1.length) {

		grid_width = 2;

		grid_height = tiles1.length;

	}



	$('message_text').fade('hide'); // make message text invisible.

	$('message_box').setStyle('visibility', 'visible'); // don't need to hide this any more

	scoreFormSlider = new Fx.Slide('score_form').hide();

	playAgainSlider = new Fx.Slide('play_again_box').hide();



	buildDeckData();

	drawGrid();

	getScores();

});



// Builds the 'deck' variable - a hash of hashes

function buildDeckData() {

	for (var i = 0; i < tiles1.length; i++) {

		deck.set('card' + i + 'a', new Hash({

				card_number : i,

				img_src : img_folder + tiles1[i]

			})

		);

		deck.set('card' + i + 'b', new Hash({

				card_number : i,

				img_src : img_folder + tiles2[i]

			})

		);

	}

}



// Draw the grid of cards for the first time

function drawGrid() {

	var allCardKeys = deck.getKeys();

	$('card_table').empty();

	for (var row = 0; row < grid_height; row++) {

		// Add row

		var rowEl = new Element('tr');



		for (var col = 0; col < grid_width; col++) {

			var key = allCardKeys.getRandom();

			allCardKeys.erase(key);



			// Add column.  td contains a div, which contains an img

			var colEl = new Element('td', {

				'align' : 'center',

				'class' : 'blk'

			});

			var cardEl = new Element('div', { 'id' : key });

			cardEl.addEvent('click', function() {

				clickedCard(this.get('id'));

			}.bind(cardEl));



			cardEl.grab(

				new Element('img', {

					'src' : back,

					'width' : '60',

					'height' : '60',

					'alt' : 'card'

				})

			);

			colEl.grab(cardEl);

			rowEl.grab(colEl);

		}



		$('card_table').grab(rowEl);

	}

}



function showCard(cardElement) {

	var imgEl = cardElement.getChildren()[0];

	var key = cardElement.get('id');

	imgEl.set('src', deck.get(key).get('img_src'));

}

function hideCard(cardElement) {

	var imgEl = cardElement.getChildren()[0];

	imgEl.set('src', back);

}



// Resets the whole game.

function playAgain() {

	cards_showing = [];

	cards_matched = [];

	num_seconds = 0;

	num_moves = 0;

	clearInterval(timer_game);

	timer_game = false;

	$('counter').set('html', '0:00');

	playAgainSlider.slideOut();

	scoreFormSlider.slideOut();

	hideInfo();

	hideMessage();

	buildDeckData();

	drawGrid();

}



// cardElement is the div

function clickedCard(key_clicked) {

	var cardElement = $(key_clicked);



	if (!timer_game) {

		clearInterval(timer_game);

		timer_game = setInterval('timeCallback()', 1000);

	}



	// Ignore if the card is already showing.

	if (cards_showing.contains(key_clicked)) {

		return;

	}

	// Should never happen - since we remove the click event from matched cards

	if (cards_matched.contains(key_clicked)) {

		return;

	}



	// If there are 2 cards showing and you click another

	if (cards_showing.length == 2) {

		clearTimeout(timer_card);

		conceal(); // Note conceal() emptys cards_showing

	}



	// No cards showing and you click one, just show it.

	if (cards_showing.length == 0) {

		cards_showing[0] = key_clicked;

		showCard(cardElement);



	// If one was showing and you clicked another, check for a match

	} else if (cards_showing.length == 1) {

		num_moves++;



		var key_old = cards_showing[0];

		cards_showing[1] = key_clicked;



		showCard(cardElement);



		// Cards matched!

		if (deck.get(key_clicked).get('card_number') == deck.get(key_old).get('card_number')) {

			cardElement.removeEvents('click');

			$(key_old).removeEvents('click');

			

			cards_showing = [];

			cards_matched.include(key_old);

			cards_matched.include(key_clicked);



			if (cards_matched.length == deck.getLength()) {

				notifyMatch(key_old, key_clicked);

				gameOver();

			} else {

				notifyMatch(key_old, key_clicked);

			}



		// Cards didn't match

		} else {

			timer_card = setTimeout('conceal()', 900);

		}

	}

}



function conceal() {

	cards_showing.each(function(key, index) {

		hideCard($(key));

	})

	cards_showing.empty();

}



// This function gets fired when those two cards get matched.

var timer_info;

function notifyMatch(key1, key2) {

	var message;

	if (!info_enabled) {

		return;

	}

	var i = deck.get(key1).get('card_number');

	message = info[i];



	clearTimeout(timer_info);

	$('info_text').set('html', message);

	$('info_text').fade('in');

	if (info_timeout) {

		timer_info = setTimeout('hideInfo()', info_timeout * 1000);

	}

}

function hideInfo() {

	$('info_text').fade('out');

}



function timeCallback() {

	num_seconds++;

	var min = Math.floor(num_seconds / 60);

	var sec = num_seconds % 60;

	$('counter').set('html', min + ':' + (sec<10 ? '0' : '') + sec);

}



function gameOver() {

	clearInterval(timer_game);

	clearTimeout(timer_card);

	timer_game = false;



	if (scores_enabled) {

		checkForQualifyingScore();

	} else {

		playAgainSlider.slideIn();

	}

}



var jsonRequest;

function checkForQualifyingScore() {

	if (jsonRequest) {

		jsonRequest.cancel();

	}

	jsonRequest = new Request.JSON({url:score_url, onComplete:function(rv) {

		playAgainSlider.slideIn();

		if (rv) {

			if (rv.score_qualifies) {

				showMessage('Congratulations! You made it into the high score list. Submit your score below.', 1);

				scoreFormSlider.slideIn();

			} else {

				showMessage('Sorry, your score did not qualify.', 1);

			}

		} else {

			showMessage('<strong>Error checking scores.</strong>');

		}

	}});

	var email = $('email_id').get('value');

	if (!email) {

		email = "";

	}

	jsonRequest.get({'action':'check_score','num_moves':num_moves,'time':num_seconds,'email':email});

}



function submitScore() {

	if (jsonRequest) {

		jsonRequest.cancel();

	}

	jsonRequest = new Request.JSON({url:score_url, onComplete:function(rv) {

		if (rv) {

			if (rv.score_written) {

				showMessage('<strong>Score saved.</strong>');

				getScores();

			} else {

				showMessage('<strong>Could not save your score.</strong>');

			}

		} else {

			showMessage('<strong>Error saving your score.</strong>');

		}

	}});

	jsonRequest.get({'action':'submit_score','num_moves':num_moves,'time':num_seconds, 'name':$('name_id').get('value'), 'email':$('email_id').get('value')});

	scoreFormSlider.slideOut();

	return false; // This keeps the form from submitting normally

}



var scores = [];

function getScores() {

	if (jsonRequest) {

		jsonRequest.cancel();

	}

	jsonRequest = new Request.JSON({url:score_url, onComplete:function(rv) {

		if (rv) {

			scores = rv;

			drawScoreTable();

		}

	}});

	jsonRequest.get({'action':'get_scores'});

}



// this assumes the 'scores' var is populated.

function drawScoreTable() {

	$('score_table').empty();

	for (var i = 0; i < scores.length; i++) {

		var score = scores[i];

		var theTime = Math.floor(score.time / 60);

		var numSecs = score.time % 60;

		theTime += ':' + (numSecs < 10 ? '0' : '') + numSecs;



		var rowEl = new Element('tr');

		if (i % 2) {

			rowEl.set('class', 'alt');

		}

		rowEl.grab(new Element('td', { html : score.name }));

		rowEl.grab(new Element('td', { html : theTime }));

		rowEl.grab(new Element('td', { html : "in " + score.num_moves + " moves" }));



		$('score_table').grab(rowEl);

	}

}



var timer_message;

function showMessage(msg, dont_hide) {

	clearTimeout(timer_message);

	$('message_text').set('html', msg);

	$('message_text').fade('in');

	if (dont_hide === undefined) {

		timer_message = setTimeout('hideMessage()', 2000);

	}

}

function hideMessage() {

	$('message_text').fade('out');

}



