function disable_cell(element, color)
{
	Event.stopObserving(element);
	element.setStyle({'cursor': 'not-allowed'});
	element.src = element.src.replace(/\/images\/f\//, '/images/f/' + color +'/');
}
function disable_field(winner_guid)
{
	var color;
	if(winner_guid == PLAYER_GUID){
		color = 'green';
	}else
	{
		color = 'bw';
	}
	$$('#field img').map(function(i) {disable_cell(i, color)});
}
function get_cell_value(x, y)
{
	var cell_id = "c" + x + "-" + y;
	return $(cell_id).src.match(/\/(\w+)\.gif$/)[1];
}
function blink_cell(x, y)
{
	var cell = $("c" + x + "-" + y);
	set_cell_img(cell, '0');
	setTimeout("set_cell_img($('c" + x + "-" + y + "'), 'fog');", 200);
}
function get_surrounding_flag_count(x, y)
{
	var result = 0;
	for (i = x - 1; i <= x + 1; i++)
	{
		for (j = y - 1; j <= y + 1; j++)
		{
			if (i >= 0 && j >= 0 && i < FIELD_WIDTH && j < FIELD_HEIGHT)
			{
				if (get_cell_value(i, j) == 'flag')
				{
					result++;
				}
			}
		}
	}
	return result;
}
function get_surrounding_count(x, y, cell_value)
{
	var result = 0;
	for (i = x - 1; i <= x + 1; i++)
	{
		for (j = y - 1; j <= y + 1; j++)
		{
			if (i >= 0 && j >= 0 && i < FIELD_WIDTH && j < FIELD_HEIGHT)
			{
				if (get_cell_value(i, j) == cell_value)
				{
					result++;
				}
			}
		}
	}
	return result;
}
function get_surrounding_fog_count(x, y)
{
	return get_surrounding_count(x, y, 'fog');
}
function get_surrounding_fired_bomb_count(x, y)
{
	return get_surrounding_count(x, y, 'loser') + get_surrounding_count(x, y, 'bomb');
}
function handle_middle_click(x, y)
{
	if(get_surrounding_fog_count(x, y) != 0)
	{
		var should_send_click = false;
		if ((get_surrounding_flag_count(x, y) + get_surrounding_fired_bomb_count(x, y)).toString() >= get_cell_value(x, y))
		{
			//Event.stopObserving('c' + x + '-' + y);
			should_send_click = true;
		}
		for (i = x - 1; i <= x + 1; i++)
		{
			for (j = y - 1; j <= y + 1; j++)
			{
				if (i >= 0 && j >= 0 && i < FIELD_WIDTH && j < FIELD_HEIGHT)
				{
					if (get_cell_value(i, j) == 'fog')
					{
						if(should_send_click)
						{
							set_cell_img($('c' + i + '-' + j), 'loading');
						}else
						{
							blink_cell(i, j);
						}
					}
				}
			}
		}
		if(should_send_click){
			send_click(x, y, 'm');
		}
	}
}
function cell_clicked(event)
{
	var cell = event.element();//findElement();
	var x = parseInt(cell.id.match(/c(\d+)\-\d+/)[1]);
	var y = parseInt(cell.id.match(/c\d+\-(\d+)/)[1]);
	
	var button = 'l';
	if (event.type == 'dblclick')
	{
		button = 'm';
	}else
	{
		if (event.which == null)
		       /* IE case */
		       button= (event.button < 2) ? "l" :
		                 ((event.button == 4) ? "m" : "r");
		    else
		       /* All others */
		       button= (event.which < 2) ? "l" :
		                 ((event.which == 2) ? "m" : "r");
	}
	if (button == 'l') {
		if (get_cell_value(x, y) == 'fog') {
			//Event.stopObserving('c' + x + '-' + y, 'mouseup');
			set_cell_img(cell, 'loading');
			send_click(x, y, button);
		}
	}else if (button == 'r'){
		if (get_cell_value(x, y) == 'fog' || get_cell_value(x, y) == 'flag'){
			set_cell_img(cell, 'loading');
			send_click(x, y, button);
		}
	}else if (button == 'm')
	{
		handle_middle_click(x, y);
	}
	
	return false;
}
function send_click(x, y, button)
{
	new Ajax.Request('/api/move?x=' + x + '&y=' + y + '&b=l' + '&g=' + GAME_GUID + '&b=' + button + '&p=' + PLAYER_GUID + '&s=' + SECRET);
	//stomp.send('x_' + x + '-y_' + y + '-g_' + GAME_GUID + '-b_' + button + '-p_' + PLAYER_GUID + '-s_' + SECRET, 'move');
}
function is_open(x, y) {
	var val = get_cell_value(x, y)
	return val != 'fog' && val != 'loading';
}
function open_cells(array_str)
{
	var array = array_str;//eval(array_str);
	for(i = 0; i < array.length; i++)
	{
		var coord = array[i];
		if(is_open(coord[0], coord[1]) == false){
			open_cell(coord[0], coord[1], coord[2], coord[3]);
		}
	}
}
function reveal_solved_field()
{
	for(var x = 0; x < FIELD_WIDTH; x++)
	{
		for(var y = 0; y < FIELD_HEIGHT; y++)
		{
			if(get_cell_value(x, y) == 'flag')
			{
				open_cell(x, y, 'bomb');
			}
		}
	}
}
function open_cell(x, y, img, pl_guid)
{
	var cell = $("c" + x + "-" + y);
	var new_img = img;
	if (img == 'loser' && pl_guid != PLAYER_GUID) {
		new_img = 'bomb';
	}
	set_cell_img(cell, new_img);
	if (new_img == 'loser'|| new_img == 'bomb'){
		show_impact_for(x, y, pl_guid);
	}
}

function show_field() {
	$$("#field img").each(function(n){n.show()});
}
function set_cell_img(cell_element, file_name)
{
	cell_element.src = ASSET_HOST + '/images/f/' + file_name + '.gif';
}
function remove_all_flags_for(pl_guid)
{
	if (pl_guid == PLAYER_GUID){
		$$('#field img').each(
			function(elem, index)
			{
				if (elem.src.indexOf('flag') != -1)
				{
					var flag_id = 'flag_' + elem.id + Math.floor(Math.random()*10000);
					var flag = new Element('img', {'id': flag_id});
					set_cell_img(flag, 'flag');
					flag.setStyle({'position': 'absolute', 'top': elem.cumulativeOffset()[1] + 'px', 'left' : elem.cumulativeOffset()[0] + 'px'});
					document.body.insert(flag);
					set_cell_img(elem, 'fog');
					new Effect.Shrink(flag.id, {'duration': 0.3});
					setTimeout("$('" + flag.id + "').remove()", 1000);
				}
			}	
		);
	}
}

function join_game_nick_changed(){
	if ($('join_game_nick').value == '')
	{
		$('join_game_button').disable();
	}else
	{
		$('join_game_button').enable();
	}
}
function start_countdown(){
	blink('#90EE90');
	$("waiting_for_players").hide();
	//$('chat_list').insert('<li class="bot" id="starting_game_li"><span class="important">Starting game</span> in 5</li>');
	var field = $("field");
	field.setStyle({"background": "url(" + ASSET_HOST + "/images/countdown/5.gif) no-repeat center"});
	var countdown_timer = 4;
	new PeriodicalExecuter(function(pe) {
		if (countdown_timer <= 0)
		{
			field.setStyle({"background": "url(" + ASSET_HOST + "/images/countdown/go.gif) no-repeat center"});
			pe.stop();
			if (PLAYER_GUID == GAME_STARTER_GUID)
			{
				new Ajax.Request('/api/start_game?g=' + GAME_GUID +'&s=' + SECRET, {asynchronous:true, evalScripts:true});
			}
		}else
		{
				field.setStyle({"background": "url(" + ASSET_HOST + "/images/countdown/" + countdown_timer + ".gif) no-repeat center"});
		}
		countdown_timer--;
	}, 1);
}
function set_field_spinning_background(set){
	var field = $("field");
	if(set == true)
	{
		field.setStyle({"background": "url(" + ASSET_HOST + "/images/loading.gif) no-repeat center"});
	}else
	{
		field.setStyle({"background": "none"});
	}
}

function start_waiting_for_juggernaut_to_load(step) {
	switch(step) {
		case 'start':
			JUGGERNAUT_WAITER = setTimeout( "start_waiting_for_juggernaut_to_load('timeout_1')", 5000 );
			document.observe("juggernaut:connected", function(event) { 
				start_waiting_for_juggernaut_to_load('connected');
			});
			document.observe("juggernaut:initialized", function(event) { 
				start_waiting_for_juggernaut_to_load('initialized');
			});
			break;
		case 'timeout_1':
			alert('Cannot init Juggernaut :-(');
			break;
		case 'timeout_1':
			alert('Juggernaut cannot connect :-(');
			break;
		case 'connected':
			clearTimeout(JUGGERNAUT_WAITER);
			break;
		case 'initialized':
			clearTimeout(JUGGERNAUT_WAITER);
			JUGGERNAUT_WAITER = setTimeout( "start_waiting_for_juggernaut_to_load('timeout_2')", 5000 );
			break;
	}
}

function put_flag(x, y, put) {
	var img = 'flag';
	if (put == false){
		img = 'fog';
	}
	set_cell_img($('c' + x + '-' + y), img);
}

