
/* General Functions */

function sendrequest(cmd, args, fn){
    $.post('/scgi-bin/quest?' + cmd + ' ' + args, fn, "json");
    return true;
}

function quote(str){
    if (!str.indexOf('"')){
	return '"' + str + '"';
    } else if (!str.indexOf("'")){
	return "'" + str + "'";
    } else {
	return '[' + str + ']';
    }
}

function checkforlocations(){ 
    $('.location').click(function(e){
	    e.preventDefault();
	    findlocation(this.getAttribute('location'));
	    });
	   

    return true;
}


function findlocation(where){
    if (!where) return;

    sendrequest("find",quote(where), findlocation_cb);
    return true;
}


function findlocation_cb(data){
    var loc = data.locations[0];
    var dialog = $('#locationinfo');
    var x,y;

    dialog.html('<span class="loctitle">' + loc.name + '</span><br/>' +
	'<div class="right"><a href="#" id="finddismiss" class="medium green awesome">Okay</a></div>');
    dialog.show();

    $('#finddismiss').click(findlocation_dismiss);

    var x = loc.x;
    var y = loc.y;
    x = x - curpos.x;
    y = y - curpos.y;
    // the (x+y -1) for subtracting half a tile width
    var xpos = centerx + dx * (x + y - 1); 
    var ypos = centery + dy * (y - x);
    
    var onmap = true;
    if (xpos < 0 || ypos < 0 || xpos > centerx * 2 || ypos > centery * 2){
	onmap = false;
    }

    /* On the map: Just put the popup near it. */
    if (onmap){
	dialog[0].style.left = "" + xpos + "px";
	dialog[0].style.top = "" + ypos + "px";
	dialog.append("Xpos: " + xpos + " Ypos: " + ypos);
	return true;
    }
   
    // FIXME: Hard coded
    var angle = Math.atan2(ypos - centery, xpos - centerx);
    angle += Math.PI / 2;
    dialog[0].style.left = "" + 300 + "px";
    dialog[0].style.top = "" + 300 + "px";
    dialog.append("Xpos: " + xpos + " Ypos: " + ypos);
    dialog.append("Angle: " + angle);
    dialog.append("<canvas id='arrow' width='200' height='200'></canvas>");
    
    var drawingCanvas = document.getElementById('arrow');
    if(drawingCanvas.getContext) {
	var context = drawingCanvas.getContext('2d');
	var aimg = new Image();
	aimg.onload = function() {
	    context.translate(100,100);
	    context.rotate(angle);
	    context.drawImage(aimg, -71, -71,142,142);
	}
	aimg.src = "arrow.png";
    }

    return true;
}

function findlocation_dismiss(){
    $('#locationinfo').hide();
    return true;
}


/* vim: set sw=4 sts=4 syn=javascript : */

