var gb_joystick = null;
var gb_joystick_offset = null;
var gb_stop_timer = null;
var gb_mouse_move_count = 0;
Event.observe(window,'load',function(){gb_init();},1000);

var position = 6;
var speed = 0;

function gb_init() {
    //create joystick
    var el = $('joystick');
    gb_joystick_offset = Position.page(el);

    el.style.width=200;
    el.style.height=200;
    el.style.border='1px solid black';
    el.style.position="relative";

    //attach mousemove observers
    Event.observe(el,"mousemove",function(event){gb_event_handler(event);},false);


    gb_joystick = new jsGraphics("joystick");
    gb_draw_center();
    gb_send("eye",{});
    setInterval(function(){gb_update_eye();}, 500);
}

function gb_send(action, params) {
//    new Ajax.Request('bot?action='+action,{method: 'get',parameters : params});
    if (action == 'stop') {
        speed = 0;
    } else if (action == 'drive' ) {
        var y = 100-params.y;
        if (Math.abs(y)<5) {
            speed = 0;
        } else {
            speed = 1;
            if (y < 0) {
                speed = -speed;
            }
        }
    }
}

function gb_update_eye() {
    position += speed;
    position = Math.min(position, 13);
    position = Math.max(position, 1);
    $('eye').src='walk/w'+position+'.jpg';
}

function gb_stop() {
    gb_send('stop',{});
}

function gb_event_handler(event) {
    if ('mousemove'==event.type) {
        if (gb_mouse_move_count++ % 4) {
            return;
        }
        var x = Event.pointerX(event) - gb_joystick_offset[0];
        var y = Event.pointerY(event) - gb_joystick_offset[1];
        gb_redraw_control(x,y);
        gb_send('drive',{x:x,y:y});
        if (null != gb_stop_timer) {
            clearTimeout(gb_stop_timer);
        }
        gb_stop_timer = setTimeout("eval(gb_stop())",5000);
    }
}

function gb_draw_center() {
	gb_joystick.setColor("#ffffff");
	gb_joystick.fillEllipse(100,100,3,3);
	gb_joystick.paint();
}

function gb_redraw_control(x,y) {
    var msgarea = $('msgarea');

    gb_joystick.clear();
    gb_draw_center();

    gb_joystick.setStroke(1);
    gb_joystick.setColor("#ffffff");
    gb_joystick.drawLine(x,0,x,201);
    gb_joystick.drawLine(0,y,201,y);
    gb_joystick.paint();
}