/*
 * wargame.js
 * Copyright 2010 Johan Schön
 */

$(document).ready(function(){
	var scroll=WG.hex2xy(WG.getHexXY());
	$('#mapImgPane').scrollTo({top:scroll.y-$('#mapPane').innerHeight()/2+22, left:scroll.x-$('#mapPane').innerWidth()/2+26}, 0);
	$('#selected').animate({top:scroll.y-22, left:scroll.x-26},0);
	$('#mapimg').mousedown(
		function (e) {
			var pos=$(this).position();
			WG.newHex=WG.xy2hex({x:e.pageX-pos.left-134,y:e.pageY-pos.top-3});
			return false;
		}
	);
	$('#mapimg').mouseup(WG.updateSelected);
	$('#selectedimg').mousedown( function (e) { return false; });
	$('div.otherunit').mousedown(WG.ou_mousedown);
	$('div.otherunit').mouseup(WG.updateSelected);
	$('div.playerunit').mouseup(WG.updateSelected);
	$('div.playerunit').mousedown(WG.pu_mousedown);
	$('div.playerunit').draggable(WG.pu_draggable);
	$('#logoPane').click(function(e){
		var dHex= {x:Math.floor((e.pageX-3)/2),y:Math.floor((e.pageY-3-Math.floor((e.pageX-3)/2)%2)/2)};
		var dXY=WG.hex2xy(dHex);
		if (document.getElementById('mapImgPane'))
		{
			$('#mapImgPane').scrollTo({top:dXY.y-$('#mapPane').innerHeight()/2+22, left:dXY.x-$('#mapPane').innerWidth()/2+26}, 1200);
			WG.newHex.x=dHex.x;
			WG.newHex.y=dHex.y;
			WG.updateSelected();
		}
		else
		{
			if (dHex.x<0) dHex.x=0;
			if (dHex.x>63) dHex.x=63;
			if (dHex.y<0) dHex.y=0;
			if (dHex.y>63) dHex.y=63;
			window.location='/map/x'+dHex.x+'y'+dHex.y;
		}
	});
	WG.game="g"+$('#game').text();
	WG.player="p"+$('#player').text();
});

var WG=new Object();
WG.processing=false;
WG.noDragging=false;
WG.hex_x_offset=31;
WG.hex_y_offset=26;
WG.hex_width=41;
WG.hex_height=42;
WG.startHex={x:-1, y:-1};
WG.lastHex={x:-1, y:-1};
WG.newHex={x:-1, y:-1};
WG.path='';
WG.maxPathLength=0;
WG.started=false;
WG.player=false;
WG.game=false;
WG.unit=false;

WG.getHexXY=function()
{
	var xy=$('#hex').text();
	var hex={x:0, y:0};
	var pattern=/^Hex: x(\d*)y(\d*)/;
	var r=xy.match(pattern);
	if (r!=null) {
		hex.x=r[1];
		hex.y=r[2];
	}
	return hex;
}

WG.xy2hex=function(xy)
{
	var hex=new Object();
	var d;
	hex.x=Math.round((xy.x-WG.hex_x_offset)/WG.hex_width);
	d=hex.x%2*WG.hex_height/2;
	hex.y=Math.round((xy.y-WG.hex_y_offset-d)/WG.hex_height);
	if (hex.x<0) hex.x=0;
	if (hex.x>63) hex.x=63;
	if (hex.y<0) hex.y=0;
	if (hex.y>63) hex.y=63;
	return hex;
}

WG.hex2xy=function(hex)
{
	var xy=new Object();
	xy.x=WG.hex_x_offset+hex.x*WG.hex_width;
	xy.y=WG.hex_y_offset+hex.y*WG.hex_height+(hex.x%2)*WG.hex_height/2;
	return xy;
}

WG.distance=function(startHex, endHex)
{
	var dX=Math.abs(startHex.x-endHex.x);
	var dY=Math.abs(startHex.y-endHex.y);
	var w;
	if (startHex.y<endHex.y)
		w=startHex.x%2;
	else
		w=(startHex.x+1)%2;
	dY=dY-Math.floor((dX+w)/2);
	if (dY<0)
		dY=0;
	return dX+dY;
}

WG.step=function(startHex, d)
{
	var endHex=new Object();
	endHex.x=startHex.x;
	endHex.y=startHex.y;
	if (d==5 || d==6)
		endHex.x--;
	if (d==2 || d==3)
		endHex.x++;
	if (d==1)
		endHex.y--;
	if (d==4)
		endHex.y++;
	if (startHex.x%2==1 && (d==3 || d==5))
		endHex.y++;
	if (startHex.x%2==0 && (d==6 || d==2))
		endHex.y--;
	return endHex;
}

WG.move=function(startHex, path)
{
	var i;
	var endHex;
	endHex={x:startHex.x,y:startHex.y};
	for (i=0; i<path.length; i++)
		endHex=WG.step(endHex, path.charAt(i));
	return endHex;
}

WG.getDir=function(startHex, endHex)
{
	if (startHex.x==endHex.x)
	{
		if (startHex.y<endHex.y)
			return '4';
		if (startHex.y>endHex.y)
			return '1';
		return '';	
	}
	else
	{
		if (startHex.x<endHex.x)
		{
			if (startHex.x%2)
			{
				if (startHex.y>=endHex.y)
					return '2';
				else
					return '3';
			}
			else
			{
				if (startHex.y>endHex.y)
					return '2';
				else
					return '3';
			}
		}
		else
		{
			if (startHex.x%2)
			{
				if (startHex.y>=endHex.y)
					return '6';
				else
					return '5';
			}
			else
			{
				if (startHex.y>endHex.y)
					return '6';
				else
					return '5';
			}
		}
	}
}


WG.normalizePath=function(startHex, path, hex)
{
	var i;
	var endHex;
	var newPath='';
	if (startHex.x==hex.x && startHex.y==hex.y)
		return '';
	endHex={x:startHex.x,y:startHex.y};
	for (i=0; i<path.length; i++)
	{
		endHex=WG.step(endHex, path.charAt(i));
		newPath=newPath+path.charAt(i);
		if (endHex.x==hex.x && endHex.y==hex.y)
			break;
	}
	var shorter=true;
	while (newPath.length>1 && shorter)
	{
		var twoBackHex=WG.move(startHex,newPath.substr(0,newPath.length-2))
		if (WG.distance(twoBackHex, hex)==1)
		{
			newPath=newPath.substr(0,newPath.length-2)+''+WG.getDir(twoBackHex, hex);
		}
		else
		{
			shorter=false;
		}
	}
	if (newPath.length>WG.maxPathLength)
		newPath=newPath.substr(0,WG.maxPathLength);
	return newPath;
}

WG.updateArrows=function()
{
	var i;
	var x;
	var y;
	var ad=''
	var ai=''
	var as='/img/arrow0.png';
	var pos;
	var xypos;
	pos=WG.startHex;
	for (i=0; i<WG.path.length; i++)
	{
		pos=WG.step(pos, WG.path.charAt(i));
		ad='#arrow'+(i+1);
		ai='#arrow'+(i+1)+'img';
		as='/img/arrow'+WG.path.charAt(i)+'.png';
		xypos=WG.hex2xy(pos);
		x=xypos.x-43;
		y=xypos.y-43;
		$(ai).attr('src', as).fadeTo(0, 0.75);
		$(ad).css('top', y).css('left', x);
	}
	for (i=WG.path.length; i<9; i++)
	{
		pos=WG.step(pos, WG.path.charAt(i));
		ad='#arrow'+(i+1);
		ai='#arrow'+(i+1)+'img';
		as='/img/arrow0.png';
		x=-100;
		y=-100;
		$(ad).css('top', y).css('left', x);
		$(ai).attr('src', as);
	}
}

WG.updateSelected=function() 
{
	$('#theHexagon').html('<div id="hexdiv" class="orange"><p><span id="hex">Hex: x'+WG.newHex.x+'y'+WG.newHex.y+ '</span></p></div>');
	$('#theHexagon').load('/ajax/gethex/x'+WG.newHex.x+'y'+WG.newHex.y,null,
		function() {
			var hex=WG.hex2xy(WG.newHex);
			$('#selected').animate({top:hex.y-22, left:hex.x-26},0);
			}
		);
}

WG.ou_mousedown=function (e) 
{
	WG.newHex=WG.xy2hex({x:this.offsetLeft+16,y:this.offsetTop+16});
	return false;
}

WG.pu_mousedown=function (e) 
{
	if (WG.processing)
	{
		WG.newHex=WG.xy2hex({x:this.offsetLeft+16,y:this.offsetTop+16});
		return false;
	}
	WG.started=true;
	WG.startHex=WG.xy2hex({x:this.offsetLeft+16,y:this.offsetTop+16});
	WG.path='';
	var m=$(this).find('p').text();
	WG.maxPathLength=m.substring(m.length-1,m.length);
	WG.lastHex.x=WG.startHex.x;
	WG.lastHex.y=WG.startHex.y;
	WG.newHex.x=WG.startHex.x;
	WG.newHex.y=WG.startHex.y;
	var mHex=WG.move(WG.startHex, WG.path);
	$('#animation').css('top', -100).css('left', -100);
	WG.unit=$(this).attr('id')
	return true;
}

WG.pu_draggable=
{
	helper: 'clone', 
	containment: '#mapimg', 
	scroll: false, 
	cursor: 'move', 
	zIndex:900,
	opacity:0.5,
	drag: function(e, u) {
		if (!WG.started)
		{
			return false;
		}
		var xy=new Object();
		if (WG.processing || WG.noDragging ) 
		{
			WG.noDragging=true;
			return false;
		}
		xy.x=u.position.left+16;
		xy.y=u.position.top+16;
		var hex=WG.xy2hex(xy);
		if (WG.lastHex.x==hex.x && WG.lastHex.y==hex.y)
			return true;
		WG.path=''+WG.path+WG.getDir(WG.lastHex, hex);
		WG.path=WG.normalizePath(WG.startHex, WG.path, hex);
		var mHex=WG.move(WG.startHex, WG.path);
		WG.lastHex.x=mHex.x;
		WG.lastHex.y=mHex.y;
		WG.updateArrows();
	},
	stop: function(e, u) {
		if (WG.processing || WG.noDragging) 
		{
			WG.noDragging=false;
			return false;
		}
		WG.started=false;
		that=this;
		WG.processing=true;
		$.ajax({
			url:'/ajax/play/'+WG.game+'/'+WG.player+'/'+WG.unit,
			type: 'POST',
			contentType: 'application/json',
			processData: false,
			dataType: 'json',
			data: $.toJSON({
				secret:'none',
				e:$('#event').text(),
				order:'move',
				path:WG.path,
				startHex:WG.startHex
			}),
			timeout: 30000,
			error: function(a,err,b){
				WG.path='';
				WG.updateArrows();
				$('#animation').css('top', -100).css('left', -100);
				WG.processing=false;
				WG.display_msg('Communication error!');
			},
			success: function(data, err){
				if (data==null){
					WG.display_msg('Communication error!');
					WGE.new_events(0,0,[]);
				}
				else
				{
					if (data.result=='OK')
					{
						if (data.msg)
							WG.display_msg(data.msg);
						else
							WG.remove_msg();
						WGE.new_events(data.event_start, data.event_end, data.events);
					}
					else
					{
						if (data.msg)
							WG.display_msg(data.msg);
						WGE.new_events(0,0,[]);
					}
				}
				WG.path='';
				WG.updateArrows();
			}
				
		});
		$('#animation').css('top', 7).css('left', $('#mapPane').innerWidth()/2-60).fadeTo(0, 0.75).css('visibility','visible');
	}
}

WG.remove_msg=function() {
	$('#msg').css('top',-100).css('left',-100).css('right',50).css('z-index', 0).css('visibility','hidden');
	$('#msgtxt').text('');
}

WG.display_msg=function(msg) {
	$('#msgtxt').text(msg);
	var w=$('#mapPane').innerWidth()/4;
	$('#msg').css('visibility','visible').css('top',50).css('left',w).css('right',w).css('z-index', 1000).fadeTo(1,1).fadeTo(6000,0.8).fadeTo(3000,0,WG.remove_msg);
}

WGE=new Object();
WGE.first_event=0;
WGE.last_event=0;
WGE.current_event=0;
WGE.events=[];
WGE.last_unit=0;
WGE.last_unit_z=0;
WGE.explosion=false;
WGE.img=['blank','inf','arm','nav','mar'];
WGE.timeout=false;

WGE.new_events=function(first_event, last_event, events)
{
	if (WGE.current_event==0)
	{
		WGE.first_event=first_event;
		WGE.last_event=last_event;
		WGE.events=events;
		WGE.current_event=first_event;
		WGE.process_events();
		return;
	}	
}

WGE.process_events=function()
{
	var e;
	var u;
	var hex;
	var adm;
	var old_xy;
	var new_xy;
	var src;
	var klass;
	var color;
	var mov_speed;
	$('#event').text(WGE.current_event);
	if (WGE.explosion)
	{
		$('#explode').css('z.index', 0).css('top', -100).css('left', -100);
	}
	if (WGE.last_unit_z)
	{
		$('#u'+WGE.last_unit).css('z-index', WGE.last_unit_z);
	}
	else
	{
		$('#u'+WGE.last_unit).
			css('z-index', WGE.last_unit_z).
			css('top', -100).
			css('left', -100).
			css('visibility', 'hidden');
	}
	if (WGE.current_event==WGE.last_event)
	{
		WGE.first_event=0;
		WGE.last_event=0;
		WGE.current_event=0;
		WGE.events=[];
		WGE.last_unit=0;
		WG.processing=false;
		$('#animation').css('top', -100).css('left', -100);
		return;
	}
	e=WGE.events[WGE.current_event-WGE.first_event]
	WGE.current_event++;
	u=e['unit'];
	WGE.last_unit=u;
	WGE.last_unit_z=100;
	hex={x: e['x'], y: e['y']};
	adm=e['att']+'&#183;'+e['str']+'&#183;'+e['mov'];
	$('#u'+u+'adm').html(adm);
	if (e['eventtype']=='M')
	{
		old_xy=WG.hex2xy(hex);
		new_xy=WG.hex2xy(WG.step(hex, e['eventdata']));
		if (e['eventdata'] && e['eventdata']!='0')
			mov_speed=500;
		else
			mov_speed=0;
		$('#u'+u).
			css('z-index',900).
			css('top',old_xy.y-16).
			css('left',old_xy.x-16).
			animate({
			top: new_xy.y-16,
			left: new_xy.x-16
			}, mov_speed, 'linear', WGE.process_events);
	}
	else if (e['eventtype']=='E')
	{
		old_xy=WG.hex2xy(hex);
		new_xy=WG.hex2xy(hex);
		WGE.explosion=true;
		$('#explode').css('z-index', 999).css('top', old_xy.y-14).css('left', old_xy.x-14).fadeTo(0,0).fadeTo(500,1).fadeTo(1000,0, WGE.process_events);
	}
	else if (e['eventtype']=='D')
	{
		old_xy=WG.hex2xy(hex);
		new_xy=WG.hex2xy(hex);
		WGE.last_unit=u;
		WGE.last_unit_z=0;
		$('#u'+u).css('visibility', 'visible').css('z-index', 900).css('top', old_xy.y-16).css('left', old_xy.x-16).draggable('#destroy').fadeTo(0,1).fadeTo(1500,0, WGE.process_events);
	}
	else if (e['eventtype']=='C')
	{
		old_xy=WG.hex2xy(hex);
		new_xy=WG.hex2xy(hex);
		WGE.last_unit=u;
		WGE.last_unit_z=100;
		src='/img/'+WGE.img[e['type']];
		if (WG.player=='p'+e['owner'])
			src += '-w.png';
		else
			src += '-b.png';
		adm=e['att']+'&#183;'+e['str']+'&#183;'+e['mov'];
		$('#u'+u).css('z-index', 100).css('top', old_xy.y-16).css('left',old_xy.x-16);
		$('#u'+u+'adm').html(adm);
		$('#u'+u+'img').attr('src', src);
		$('#u'+u).fadeTo(0,1, WGE.process_events);
	}
	else if (e['eventtype']=='N')
	{
		old_xy=WG.hex2xy(hex);
		new_xy=WG.hex2xy(hex);
		WGE.last_unit=u;
		WGE.last_unit_z=100;
		src='/img/'+WGE.img[e['type']];
		$('#u'+u).css('z-index', 300).css('top', old_xy.y-16).css('left',old_xy.x-16).attr('src', src).css('visibility', 'visible').fadeTo(0,0);
		adm=e['att']+'&#183;'+e['str']+'&#183;'+e['mov'];
		if (WG.player=='p'+e['owner'])
		{	
			src += '-w.png';
			klass = "unit white playerunit";
			$('#u'+u).draggable(WG.pu_draggable).mouseup(WG.updateSelected).mousedown(WG.pu_mousedown);
		}
		else
		{
			src += '-b.png';
			klass = "unit black otherunit";
			$('#u'+u).draggable('destroy').mousedown(WG.ou_mousedown).mouseup(WG.updateSelected);
		}
		color=" "+['neutral','north', 'west', 'east', 'south'][Math.floor((e['owner']+2)/3)];
		$('#u'+u+'adm').html(adm).attr('class',klass);
		$('#u'+u+'img').attr('src', src).attr('class', klass);
		$('#u'+u).attr('class', klass+color).fadeTo(1500,1, WGE.process_events);
	}
	else
	{
		setTimeout("WGE.process_events()",100);
	}
}

disband=function(unit)
{
	disband_org=$('#disband').html()
	$('#disband').html('Disband unit ' + unit + '?'+'<br /><a href="javascript:disband_yes('+unit+')">&nbsp;Yes&nbsp;</a>&nbsp;&nbsp;<a href="javascript:disband_no()">&nbsp;No&nbsp;</a>');
}

disband_no=function()
{
	$('#disband').html(disband_org)
}

disband_yes=function(unit)
{
	if (WG.processing)
		return;
	WG.processing=true;
	$('#disband').html('');
	$.ajax({
			url:'/ajax/play/'+WG.game+'/'+WG.player+'/u'+unit,
			type: 'POST',
			contentType: 'application/json',
			processData: false,
			dataType: 'json',
			data: $.toJSON({
				secret:'none',
				e:$('#event').text(),
				order:'disband',
				path:'',
				startHex:WG.startHex
			}),
			timeout: 30000,
			error: function(a,err,b){
				$('#animation').css('top', -100).css('left', -100);
				WG.processing=false;
				WG.display_msg('Communication error!');
			},
			success: function(data, err){
				if (data==null){
					WG.display_msg('Communication error!');
					WGE.new_events(0,0,[]);
				}
				else
				{
					if (data.result=='OK')
					{
						if (data.msg)
							WG.display_msg(data.msg);
						else
							WG.remove_msg();
						WGE.new_events(data.event_start, data.event_end, data.events);
					}
					else
					{
						if (data.msg)
							WG.display_msg(data.msg);
						WGE.new_events(0,0,[]);
					}
				}
			}
				
		})
	$('#animation').css('top', 7).css('left', $('#mapPane').innerWidth()/2-60).fadeTo(0, 0.75).css('visibility','visible');
}

change_build=function(){
	$("#build").html(
		'New build order:<p />'+
		'<a href="javascript:change_build_to(0)">&nbsp;Nothing&nbsp;</a><p />'+
		'<a href="javascript:change_build_to(1)">&nbsp;Infantry Bde&nbsp;</a><p />'+
		'<a href="javascript:change_build_to(2)">&nbsp;Armoured Bde&nbsp;</a><p />'+
		'<a href="javascript:change_build_to(3)">&nbsp;Naval Sqn&nbsp;</a><p />'
	)
}

change_next_build=function(){
	$("#build").html(
		'Next build order:<p />'+
		'<a href="javascript:change_next_to(0)">&nbsp;Nothing&nbsp;</a><p />'+
		'<a href="javascript:change_next_to(1)">&nbsp;Infantry Bde&nbsp;</a><p />'+
		'<a href="javascript:change_next_to(2)">&nbsp;Armoured Bde&nbsp;</a><p />'+
		'<a href="javascript:change_next_to(3)">&nbsp;Naval Sqn&nbsp;</a><p />'
	)
}

change_build_to=function(b){
	$("#build").html('')
	ajax_build('build', b)
}

change_next_to=function(b){
	$("#build").html('')
	ajax_build('next', b)
}

ajax_build=function(order, b){
	$.ajax({
			url:'/ajax/build/'+WG.game+'/'+WG.player,
			type: 'POST',
			contentType: 'application/json',
			processData: false,
			dataType: 'json',
			data: $.toJSON({
				secret:'none',
				e:$('#event').text(),
				order:order,
				build:b,
				hex:WG.getHexXY()
			}),
			timeout: 30000,
			error: function(a,err,b){
				WG.display_msg('Communication error!');
			},
			success: function(data, err){
				if (data==null){
					WG.display_msg('Communication error!');
				}
				else
				{
					if (data.result=='OK')
					{
						setTimeout("WG.updateSelected()",500);
					}
					else
					{
						if (data.msg)
							WG.display_msg(data.msg);
						else
							WG.display_msg('Communication error!');
					}
				}
			}
				
		})
}

