var ajax='ajax.php';

system=new Object();
system.systemLock=false;

$(document).ready(function(){
	$('.tiletarget').click(function(){
		uiAction('movePlayer','',this);
	});
});

function uiAction(action,data,object){
	if(system.systemLock==false){
		switch(action){
			case 'movePlayer':
				//alert($('[object=player]').attr('coordx')+'x'+$('[object=player]').attr('coordy'));
				executeAjaxAction(action,('ox='+($('[object=player]').attr('coordx'))+'&oy='+($('[object=player]').attr('coordy'))+'&dx='+($(object).attr('coordx'))+'&dy='+($(object).attr('coordy'))));
			break;
			
			default:
				alert('ERROR: This action does not exist in user interface!');
		}
	}
}

function executeAjaxAction(action, valuestring){
	if(valuestring==null){
		valuestring='';
	}
	$.ajax({
		type: 'POST',
		url: ajax,
		dataType: 'json',
		cache: false,
		data: ({action : action, valuestring : valuestring}),
		success: function(json){
			parseAjaxReturn(json);
		},
		error: function(obj,msg,detailedmsg){
			alert(' FATAL ERROR: '+msg+' ('+detailedmsg+')');
		}
	});
}

function parseAjaxReturn(json){
	if(json['error']==1){
		showAlert('ERROR: '+json['alert_message']);
	} else {
		switch(json['action']){
		
			case 'moveCharacter':
				var currentDepth=parseInt($("[object=player]").attr("coordx"))+parseInt($("[object=player]").attr("coordy"));
				for(var i in json['data']){
					var bits=json['data'][i].split('x');
					var newDepth=parseInt(bits[0])+parseInt(bits[1]);
					zindex=parseInt($('[tilegraphic='+(json['data'][i])+']').css('z-index'));
					targetMarginLeft=parseInt($('[tilegraphic='+(json['data'][i])+']').css('margin-left'))+13;
					targetMarginTop=parseInt($('[tilegraphic='+(json['data'][i])+']').css('margin-top'))-3;
					setTimeout('$("[object=player]").attr("coordx",'+bits[0]+');$("[object=player]").attr("coordy",'+bits[1]+');$("[object=player]").animate({marginLeft:"'+targetMarginLeft+'",marginTop:"'+targetMarginTop+'"},290,"linear")',i*300);
					if(newDepth>currentDepth){
						setTimeout('$("[object=player]").css("z-index","'+(zindex+1)+'");',((i*300)+100));
					} else if(newDepth<currentDepth){
						setTimeout('$("[object=player]").css("z-index","'+(zindex+1)+'");',((i*300)+300));
					}
					currentDepth=newDepth;
				}
			break;
			
			case 'none':
			break;
			
			default:
				showAlert('ERROR: Callback action ['+json['action']+'] does not exist in user interface!');
		}
	}
}


