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-fr.gif', 'andorra-fr.gif', 'armenia-fr.gif', 'austria-fr.gif',

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

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

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

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

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

	'slovak-fr.gif', 'slovenia-fr.gif', 'spain-fr.gif', 'sweden-fr.gif', 'swiss-fr.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 = [

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Albanie</strong></span><br>(membre)<br>capitale: Tirana<br>adhésion: 1995',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>Andorre</strong></span><br>(membre)<br>capitale: Andorre-la-Vieille<br>adhésion: 1965',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Arménie</strong></span><br>(membre)<br>capitale: Erevan<br>adhésion: 2001',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Autriche</strong></span><br>(membre)<br>capitale: Vienne<br>adhésion: 1956',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Bosnie-Herzégovine</strong></span><br>(membre)<br>capitale: Sarajevo<br>adhésion: 2002',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Bulgarie </strong></span><br>(membre)<br>capitale: Sofia<br>adhésion: 1992',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>le Conseil de l&rsquo;Europe </strong></span><br>capitale: Strasbourg',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Croatie </strong></span><br>(membre)<br>capitale: Zagreb<br>adhésion: 1996',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>Chypre </strong></span><br>(membre)<br>capitale: Nicosie<br>adhésion: 1961',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la République tchèque </strong></span><br>(membre)<br>capitale: Prague<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Estonie</strong></span><br>(membre)<br>capitale: Tallinn<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Finlande </strong></span><br>(membre)<br>capitale: Helsinki<br>adhésion: 1989',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la France</strong></span><br>(membre fondateur)<br>capitale: Paris<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>le Royaume-Uni </strong></span><br>(membre fondateur)<br>capitale: Londres<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Allemagne</strong></span><br>(membre)<br>capitale: Berlin<br>adhésion: 1950',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Grèce </strong></span><br>(membre)<br>capitale: Athènes<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Hongrie </strong></span><br>(membre)<br>capitale: Budapest<br>adhésion: 1990',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Islande</strong></span><br>(membre)<br>capitale: Reykjavik<br>adhésion: 1950',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Irlande</strong></span><br>(membre fondateur)<br>capitale: Dublin<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Lettonie </strong></span><br>(membre)<br>capitale: Riga<br>adhésion: 1995',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>le Liechtenstein </strong></span><br>(membre)<br>capitale: Vaduz<br>adhésion: 1978',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Lituanie </strong></span><br>(membre)<br>capitale: Vilnius<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>le Luxembourg </strong></span><br>(membre fondateur)<br>capitale: Luxembourg<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>" l&rsquo;ex-République yougoslave de Macédoine " </strong></span><br>(membre)<br>capitale: Skopje<br>adhésion: 1995',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>Malte </strong></span><br>(membre)<br>capitale: la Vallette<br>adhésion: 1965',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>le Monténégro </strong></span><br>(membre)<br>capitale: Podgorica<br>adhésion: 2007',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>les Pays-Bas </strong></span><br>(membre fondateur)<br>capitale: Amsterdam<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Norvège </strong></span><br>(membre fondateur)<br>capitale: Oslo<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Pologne </strong></span><br>(membre)<br>capitale: Varsovie<br>adhésion: 1991',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Roumanie </strong></span><br>(membre)<br>capitale: Bucarest<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la République slovaque </strong></span><br>(membre)<br>capitale: Bratislava<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Slovénie </strong></span><br>(membre)<br>capitale: Ljubljana<br>adhésion: 1993',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>l&rsquo;Espagne</strong></span><br>(membre)<br>capitale: Madrid<br>adhésion: 1977',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Suède </strong></span><br>(membre fondateur)<br>capitale: Stockholm<br>adhésion: 1949',

'Vous avez trouvé:<br><span style="font-size:larger; "><strong>la Suisse </strong></span><br>(membre)<br>capitale: Berne<br>adhésion: 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');

}




