

var car_array =new Array();
var lock_agents_request=0;

function bad_car_icon()
{
    var bad_car = new GIcon();
    bad_car.iconSize = new GSize(30,30);
    bad_car.iconAnchor = new GPoint(15,15);
    bad_car.shadow = "";
    bad_car.image = "bil/s0.gif";
    return(bad_car);
}

function clear_all_agents()
{
    //console.info("Clearing car_array...");
    lock_agents_request++;
    while(car_array.length>0)
    {
	var car=car_array.pop();
	//console.info("Remove jwlBil "+car.id);
	gmap.removeOverlay(car.marker);
	GEvent.clearInstanceListeners(car.marker);
	delete(car.marker);
	car.marker=null;
	delete(car);
	car=null;
    }
    lock_agents_request=0;
    query_agents_in_view();
}

// Query all agents that is on the map we are folloing
function query_agents_in_view()
{
    // By putting a lock, we wont put new questions when pending once are.
    if(lock_agents_request>0)
    {
	console.warn("lock_agents_request is issued, will not execute query_agents_in_view();");
	return;
    }
    lock_agents_request++;
    
    // Qyery the db by xml-request to get all stops within map-range.
    var bnd = gmap.getBounds();
    var sw = bnd.getSouthWest();
    var ne = bnd.getNorthEast();


    // Create a new request on every try
    var Agents_View_Request = getXMLHTTPRequest();
    
    var myRandom=parseInt(Math.random()*99999999);
    
    // Add a little so we can detect if the car leave the screen.
    var nela=parseFloat(ne.lat()+0.01);
    var swla=parseFloat(sw.lat()-0.01);
    var nelo=parseFloat(ne.lng()+0.01);
    var swlo=parseFloat(sw.lng()-0.01);
    var query = "position.php" + "?rand=" + myRandom + "&nela=" +  nela.toPrecision(6) + "&nelo=" + nelo.toPrecision(6) + "&swla=" + swla.toPrecision(6) + "&swlo=" + swlo.toPrecision(6)+"&kontor_id="+kontor_id;
    Agents_View_Request.open("GET", query , true);
    
    Agents_View_Request.onreadystatechange = function()
    {
	if(!Agents_View_Request)
	    return;
	if(Agents_View_Request.readyState != 4)
	    return;
	// When readyState is 4, its the last call to this function, so we remove the lock.
	try {
	    lock_agents_request--;
	} catch(e) {}
	
	if(Agents_View_Request.status != 200)
	{
	    console.error("Agents_View_Request failed with status code: " + Agents_View_Request.status);
	    delete(Agents_View_Request);
	    Agents_View_Request=null;
	    return;
	}
	if(!Agents_View_Request.responseText || Agents_View_Request.responseText.length < 20)
	{
	    delete(Agents_View_Request);
	    Agents_View_Request=null;
	    return;
	}    
	try {
	    eval(Agents_View_Request.responseText);
	} catch (e) {
	    console.error(e);
	}
	delete(Agents_View_Request);
	Agents_View_Request=null;
    }

    Agents_View_Request.send(null);
}

jwlBil.prototype.pushData=function(course, lat, lng, valid)
{
    this.course=course;
    this.lat=lat;
    this.lng=lng;
    this.valid=valid;
    this.times++;

    if(!this.marker)
    {
	// Create Car GIcon
	var bilicon = new GIcon();
	bilicon.iconSize = new GSize(30,30);
	bilicon.iconAnchor = new GPoint(15,15);
	bilicon.shadow = "";
	bilicon.image = "bil/s0.gif";

	// Title for car icon
	var biltitle = "Klicka för att Zooma bilen! ["+this.id+"]";
	
	// Create marker
	this.marker=new GMarker(new GLatLng(this.lat,this.lng), { icon: bilicon, title: biltitle });

	// Setup event on click
	var id=this.id;
	GEvent.addListener(this.marker, "click", function() { klick_bilarid(id);});
	
	// Add to map
	gmap.addOverlay(this.marker);
    }
    
    // Om kursen ändrats
    if(this.course != this.lastcourse || valid < 1)
    {
	//console.info("Redrawing car picture.");
	var img;
	if(valid)
	    img = "bil/n"+(this.course)+".gif";
	else
	    img = "bil/s0.gif";
	this.marker.setImage(img); 
	this.lastcourse=this.course;
    }   
    
    if(this.lastlat != this.lat || this.lastlng!=this.lng)
    {
	//console.info("Moving car picture.");
	var pos2=new GLatLng(this.lat,this.lng);
	this.marker.setLatLng(pos2);
	this.lastlat=lat;
	this.lastlng=lng;
	
	// If we are tracking this agent, make sure it wont go outscreen.
	if(this.id == tracking_agent)
	{
	    var bnd = gmap.getBounds();
	    var sw = bnd.getSouthWest();
	    var ne = bnd.getNorthEast();
	    if( lat > ne.lat() ||
		lat < sw.lat() ||
		lng > ne.lng() ||
		lng < sw.lng() )
	    {
		// Counting times, make sure that user is not by force trying to drag the
		// map away from the tracking_agent, this will make sure that it wont pan back
		// twice in 10 seconds.
		if(this.times > 4)
		{
		    //console.info("Forsemoving to follow car.");
		    this.times = 0;
		    gmap.panTo(pos2);
		} else {
		    //console.info("User is dragging to hard in the map, wont follow the car anymore.");
		    tracking_agent=null;
		}
	    }
	}
    }
}

jwlBil.prototype.id=0;
jwlBil.prototype.course=0;
jwlBil.prototype.lat=0;
jwlBil.prototype.lng=0;
jwlBil.prototype.lastlat=0;
jwlBil.prototype.lastlng=0;
jwlBil.prototype.lastcourse=-1;
jwlBil.prototype.valid=0;
jwlBil.prototype.marker=null;
jwlBil.prototype.times=0;

function jwlBil(id)
{
    this.id=id;
    this.course=0;	
    this.lat=0;
    this.lng=0;
    this.lastlat=0;
    this.lastlng=0;
    this.lastcourse=-1;
    this.valid=0;
    this.marker=null;
    this.times=0;
}


function set_bil(id, course, lat, lng, valid)
{
    for(var i=0; i<car_array.length; i++)
    {
	if(car_array[i].id==id)
	{
	    //console.info("Updateing jwlBil " + id);
	    car_array[i].pushData(course, lat, lng, valid);
	    return;
	}
    }

    //console.info("Createing new jwlBil");
    var ny = new jwlBil(id);
    ny.pushData(course, lat, lng, valid);
    car_array.push(ny);
}
