//galaxy
var galaxy_link;

function anim_galaxy(){
	
	var e = $(this);
	
	galaxy_link = e.attr('href');
	
	var left = e.offset().left - e.parent().offset().left;
	var top = e.offset().top - e.parent().offset().top;
	
	e.siblings('.galaxy').fadeOut();
	
	e.css('z-index', '1000');
	e.children('IMG').animate({
								width: e.parent().width() + 'px',
								height: e.parent().height() + 'px',
								marginLeft: '-' + left + 'px',
								marginTop: '-' + top + 'px'									
				      }, function(){
				    	  location.href = galaxy_link;
				      });
	
	return false;
}


//map

var stage_top, stage_left, stage_width, stage_height, chooser, info_timer, info_hide_timer, last_tile_id, last_planet_id;

function init_map(){
	
	$('#map').mousemove(show_tile_info);
	$('#map').click(show_tile_action);
	$('#map').dblclick(hide_tile_info);
	
	stage_top = $('#stage').offset().top;
	stage_left = $('#stage').offset().left;
	stage_width = $('#stage').width();
	stage_height = $('#stage').height();

  $('#map').draggable({
		cursor: 'move',
		containment: [max_scroll_left * -1, (max_scroll_top) *-1 + stage_top, stage_left + 0, stage_top + 0],
		drag: handle_move
	});

	centerView();
	
	chooser = $('#chooser');	
}

function centerView(){
    var drag = $('#map');
    var left;
    var top;
    
	if(border_left > max_scroll_left){
        left = max_scroll_top;
    } else {
        left = border_left;
    }

    if(border_top > max_scroll_top){
        top = max_scroll_top;
    } else {
        top = border_top;
    }

//	drag.css('left', '-' + left + 'px');
//    drag.css('top', '-' + top + 'px');
    //window.status = 'centered to left: ' + left + ', top: ' + top;

   	var pos = $('#' + system_id + '_' + planet_id).position();
   	var w = $('#' + system_id + '_' + planet_id).width() / 2;
   	var h = $('#' + system_id + '_' + planet_id).height();
    	
	drag.css('left', '-' + (pos.left - max_height/2 + w) + 'px');
    drag.css('top', '-' + (pos.top - max_height/2 + h) + 'px');
    
	var m = $('#map').position();
	view_pos_y = 600 + Math.abs(m.top);
}



var cur_ui, draw_tiles;
var drawing = false;

function handle_move(event, ui){
	
	window.clearTimeout(info_timer);

	var t = $(this);
	cur_ui = ui;
	
	var map_left = ui.position.left;
	var map_top = ui.position.top;
	var map_right = map_left + t.width();
	var map_bottom = map_top + t.height();

	
    if(
    	map_left < border_left ||
        map_top < border_top ||
        map_right > border_right ||
        map_bottom > border_bottom
    ){
    	queue_tiles();
    }	
	
    if(!drawing && tile_queue.length > redraw_limit){
        draw_queue();
    }    
    	
	return false;
}

function queue_tiles(){
	
    var x_start, y_start, x_stop, y_stop;

    var view_start_x = cur_ui.position.left * -1;
    var view_start_y = cur_ui.position.top * -1;

    var view_stop_x = view_pos_x = view_start_x + stage_width;
    var view_stop_y = view_pos_y = view_start_y + stage_height;
    
    x_start = Math.floor(view_start_x / tile_w);
    y_start = Math.floor(view_start_y / tile_h * 2);

    x_stop = Math.ceil(view_stop_x / tile_w);
    y_stop = Math.ceil(view_stop_y / tile_h * 2);

    if(x_stop > size_w){
        x_stop = size_w;
    }

    if(y_stop > size_h){
        y_stop = size_h;
    }
    
    if(x_start < 0){
    	x_start = 0;
    }
    
    if(y_start < 0){
    	y_start = 0;
    }
    
    for(var y = y_start; y <= y_stop; y++){
        for(var x = x_start; x <= x_stop; x++){
            var coord = x + ',' + y;
            if(!drawn(coord) && !queued(coord)){
                tile_queue[tile_queue.length] = coord;
            }

        }
    }	
}


function draw_queue(){
	
	drawing = true;
	
	draw_tiles = tile_queue;
	tile_queue = new Array();
	
	if(!draw_tiles.length){
		return false;
	} 
	
	var needed_tiles = draw_tiles.join(';');
	
	$.getJSON(tile_url + '?galaxy_id=' + galaxy_id + '&needed_tiles=' + needed_tiles, function(data){

	    for(var i = 0; i < draw_tiles.length; i++){
	    	
	        var x = draw_tiles[i].split(',')[0];
	        var y = draw_tiles[i].split(',')[1];

	        var left = x * tile_w;
	        var top = y * tile_h/2;
	        if(y%2 == 1){
	            left += tile_w/2;
	        }

	        var tile = data[x + ',' + y];
	        var tile_markup = '';	    	

        	if ( tile[5] != null)
        	{
        		s_max = Math.max(tile[5],s_max);
        		p_max = Math.max(tile[6],p_max);
        	}
        
	        if(tile[1] == 'filler'){
				if(tile[8] != '0_0')
				{
		        	tile_markup += '<span id="' + x + '_' + y + '" class="phaeno" style="background-image: url(\'' + WEB_ROOT + '_img/tiles/' + tile_size + '/phaeno' + tile[8] + '.png\'); top: ' + top + 'px; left: ' + left + 'px; z-index:5;" ><div id="phid_' + x + '_' + y + '" style="display:none;">' + tile[9] + '_' + tile[5] + '_' + tile[6] + '</div></span>';
				}
				else
				{
		        	tile_markup = '<img id="' + x + '_' + y + '" src="' + WEB_ROOT + '_img/tiles/' + tile_size + '/' + tile[0] + '" style="left: ' + left + 'px; top: ' + top + 'px;" />';
				}
	        } else {
	        	tile_markup = '<span id="' + x + '_' + y + '" class="planet" style="background-image: url(\'' + WEB_ROOT + '_img/tiles/' + tile_size + '/' + tile[0] + '\'); left: ' + left + 'px; top: ' + top + 'px;" ><div id="p_' + x + '_' + y + '" style="display:none;">'+tile[3]+'</div>';

	        	if(tile[2] == 1){
	        		tile_markup += '<img src="' + WEB_ROOT + '_img/tiles/' + tile_size + '/' + tile[7] + '" />';
	        	}
	        	
	        	tile_markup += '</span>';

				if(tile[8] != '0_0')
				{
		        	tile_markup += '<span style="background-image: url(\'' + WEB_ROOT + '_img/tiles/' + tile_size + '/phaeno' + tile[8] + '.png\'); top: ' + top + 'px; left: ' + left + 'px; z-index:5;" ></span>';
				}
	        	
				if(tile[4] >= 100000)
				{
					var tf_size;
					
					if (tile[4] >= 10000000)
					{
						tf_size = 'tfg.png';
					}
					else if (tile[4] >= 1000000)
					{
						tf_size = 'tfm.png';
					}
					else
						tf_size = 'tfk.png';
					
		        	tile_markup += '<span id="tf_' + tile[3] + '" class="planet" style="background-image: url(\'' + WEB_ROOT + '_img/tf/' + tile_size + '/' + tf_size + '\'); top: ' + top + 'px; left: ' + left + 'px; z-index:5;" ></span>';
				}
	        	
	        }
	        
	        $('#map').append(tile_markup);
	        
	        
	        drawn_tiles[drawn_tiles.length] = draw_tiles[i];
	        
	    }	
	    
	    drawing = false;
	    
	    if(tile_queue.length){
	    	draw_queue();
	    }

		$('#debug_coord').text(galaxy_id + ':' + s_min + ':' + p_min + ' - ' + galaxy_id + ':' + s_max + ':' + p_max);	

	});
	
}

function show_tile_info(e)
{
//	mouse_left = e.clientX - stage_left - this.offsetLeft;
//	mouse_top = e.clientY - stage_top - this.offsetTop;
	mouse_left = e.pageX - stage_left - this.offsetLeft;
	mouse_top = e.pageY - stage_top - this.offsetTop;

	var posxy = getPosition(mouse_left,mouse_top);
	 
	//timer für info zurücksetzen
	if(posxy[0] + ',' + posxy[1] != last_tile_id && info_timer){
		window.clearTimeout(info_timer);
		info_timer = undefined;
	}		

	//evtl info laden
	if($('#' + posxy[0] + '_' + posxy[1]).hasClass('planet') && posxy[0] + ',' + posxy[1] != last_tile_id)
	{
		info_timer = window.setTimeout('load_planet_info("' + posxy[0] + '_' + posxy[1] + '")', 400);
	}
	else if($('#' + posxy[0] + '_' + posxy[1]).hasClass('phaeno') && posxy[0] + ',' + posxy[1] != last_tile_id)
	{
		info_timer = window.setTimeout('load_phaeno_info("' + posxy[0] + '_' + posxy[1] + '")', 400);
	}
	
	last_tile_id = posxy[0] + ',' + posxy[1];
}

function show_tile_action(e)
{
	hide_tile_info();

//	mouse_left = e.clientX - stage_left - this.offsetLeft;
//	mouse_top = e.clientY - stage_top - this.offsetTop;
	mouse_left = e.pageX - stage_left - this.offsetLeft;
	mouse_top = e.pageY - stage_top - this.offsetTop;

	var posxy = getPosition(mouse_left,mouse_top);
	
	//evtl info laden
	if($('#' + posxy[0] + '_' + posxy[1]).hasClass('planet') && posxy[0] + ',' + posxy[1] == last_tile_id)
	{
		info_timer = window.setTimeout('load_planet_action("' + posxy[0] + '_' + posxy[1] + '")', 400);
	}
	else if($('#' + posxy[0] + '_' + posxy[1]).hasClass('phaeno') && posxy[0] + ',' + posxy[1] == last_tile_id)
	{
		info_timer = window.setTimeout('load_phaeno_action("' + posxy[0] + '_' + posxy[1] + '")', 400);
	}
	
	last_tile_id = posxy[0] + ',' + posxy[1];
}

function load_planet_info(planet_id){
	
	hide_tile_info();	
	
	last_planet_id = $('#p_' + planet_id).html();
	
	var url = tile_info_url + '?modus=show&tile_id=' + last_planet_id;
	
	$.getJSON(url, function(data){
	
		if(data != 'no_info')
		{
			cur_tile = $('#' + planet_id);
			
			var html = '';
			html += '<div id="tile_info">';
			html += data['html'];
			html += '</div>';
		
			$('#map').prepend(html);			

//			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).fadeIn(100);			
			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).show();			
			$('#tile_info #close_info').click(hide_tile_info);

			window.clearTimeout(info_hide_timer);
			
			$('#fleet_info').html(data['spydata']);
			$('#tile_info').mouseout(hide_tile_info);
		}
	});
}

function load_planet_action(planet_id){

	hide_tile_info();
	
	var url = tile_info_url + '?modus=action&tile_id=' + last_planet_id;
	
	$.getJSON(url, function(data){
	
		if(data != 'no_info')
		{
			cur_tile = $('#' + planet_id);
			
			var ally = '';
			
			var html = '';
			html += '<div id="tile_info">';
			html += data['html'];
			html += '</div>';
			
			$('#map').prepend(html);
			
			$('#fleet_info').html(data['spydata']);

//			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).fadeIn(100);
			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).show();

			window.clearTimeout(info_hide_timer);
			$('#map').unbind('mousemove').unbind('click');				
		}
	});
}

function load_phaeno_info(planet_id){
	
	hide_tile_info();	
	
	last_planet_id = $('#phid_' + planet_id).html();
	
	$.post('./_ajax/ajax.get_phaeno_info.php', {tile_id:last_planet_id,modus:'show'}, function(data){
		data = data.replace(/\r\n/g,'');
		
		if(data != 'no_info')
		{
			cur_tile = $('#' + planet_id);
			
			var html = '';
			html += '<div id="tile_info">';
			html += data;
			html += '</div>';
//		
			$('#map').prepend(html);			

			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).show();			
			$('#tile_info #close_info').click(hide_tile_info);

			window.clearTimeout(info_hide_timer);
			
			$('#tile_info').mouseout(hide_tile_info);
		}
	});
}

function load_phaeno_action(planet_id){
	
	hide_tile_info();	
	
	last_planet_id = $('#phid_' + planet_id).html();
	
	$.post('./_ajax/ajax.get_phaeno_info.php', {tile_id:last_planet_id,modus:'do'}, function(data){

		if(data != 'no_info')
		{
			cur_tile = $('#' + planet_id);
			
			var ally = '';
			
			var html = '';
			html += '<div id="tile_info">';
			html += data;
			html += '</div>';
			
			$('#map').prepend(html);
			
			$('#tile_info').css('left', getLeftPos(cur_tile)).css('top', getTopPos(cur_tile)).show();

			window.clearTimeout(info_hide_timer);
			$('#map').unbind('mousemove').unbind('click');				
		}
	});
}

function hide_tile_info(){
	$('#tile_info').remove();
//	$('#tile_info').hide();
//	$('#tile_info:visible').fadeOut();
	$('#map').mousemove(show_tile_info).click(show_tile_action);

	$('#fleetcentre').html('');
}



function drawn(coord){
	if(jQuery.inArray(coord, drawn_tiles) == -1){
		return false;
	} else {
		return true;
	}
}

function queued(coord){
	if(jQuery.inArray(coord, tile_queue) == -1){
		return false;
	} else {
		return true;
	}
}

function getPosition(mouse_left,mouse_top)
{
//	mouse_left = e.clientX - stage_left - this.offsetLeft;
//	mouse_top = e.clientY - stage_top - this.offsetTop;

	var pos_x = Math.floor(mouse_left / (tile_w / 2) / 2);
	var pos_y = Math.floor(mouse_top / (tile_h / 2));
	
	var px_x = Math.floor(mouse_left % (tile_w / 2));
	var px_y = Math.floor(mouse_top % (tile_h / 2));
	
	if( Math.floor(mouse_top / (tile_h / 2) ) % 2 == 1  ){
		mouse_left += tile_w / 2;
	}
	
	if( (Math.floor(mouse_left / (tile_w / 2) )) % 2 == 0){
		
		if( -.5 * px_x + (tile_h/2) > px_y  ){
			//window.status = 'links oben';
			pos_y--;

			if(pos_y % 2 == 1){
				pos_x--;
			}

		} else {
			//window.status = 'rechts unten';
		}
		
	} else {
	
		if( .5 * px_x > px_y){
			//window.status = 'rechts oben';
			pos_y--;
			
		} else {
			//window.status = 'links unten';
			
			if(pos_y % 2 == 1){
				pos_x--;
			}
		}
	}

	//chooser positionieren
	if(pos_y > -1 && pos_x > -1 && pos_y <= size_h && pos_x <= size_w){
//		this.style.cursor = 'pointer';
		
		var chooser_left = pos_x * tile_w;
		var chooser_top = pos_y * (tile_h /2);
		
		if(pos_y % 2 == 1){
			chooser_left += tile_w / 2;
		}
		
		chooser_left = Math.floor(chooser_left);
		chooser_top = Math.floor(chooser_top);
		
		$('#chooser').css('left', chooser_left + 'px');
		$('#chooser').css('top', chooser_top + 'px');
//		chooser.css('left', chooser_left + 'px');
//		chooser.css('top', chooser_top + 'px');
	}
	
	//window.status = pos_x + ',' + pos_y;
	
	var retval = new Array(pos_x,pos_y);
	
	return retval;
}

function getLeftPos(cur_tile)
{
	var left = parseInt(cur_tile.css('left'));

	if ( (left+$('#tile_info').width()+cur_tile.width()/2) > view_pos_x )
	{
		left = parseInt(cur_tile.css('left')) - $('#tile_info').width() + cur_tile.width()/4;
	}
	else
	{
		left = parseInt(cur_tile.css('left')) + cur_tile.width()/2;
	}
	
	return left;
}

function getTopPos(cur_tile)
{
	$('#tile_info').css('height','auto');

	var p = cur_tile.position();
	var top = p.top;
	var bottom = p.top + $('#tile_info').height();

	if ( bottom > view_pos_y )
	{
		top = view_pos_y - $('#tile_info').height();
	}
	else if ( top < (view_pos_y-max_height) ) 
	{
		top = (view_pos_y-max_height) + 25;
	}
	
	return top;
}

