
// Marker red ring
var ring_marker=null;

// This variable contains the stopp_id of stop seleted, or 0 (No stopp selected)
var stopp_selected=0;

// This is a random number, regenerated by pressing s key 3 times, that will forward the
// ajax request, and make sure webrowser cache is not caching us.
var tt=0;


var titles=new Array();

// Run on load to crete the icons used for stops
function stopp_icon()
{
    icon = new GIcon();
    icon.iconSize = new GSize(20,20);
    icon.iconAnchor = new GPoint(14,18);
    icon.image = "images/t2l-bla.png";
    icon.shadow = "";
    return(icon);
}
function stoppg_icon()
{
    icon = new GIcon();
    icon.iconSize = new GSize(20,20);
    icon.iconAnchor = new GPoint(14,18);
    icon.image = "images/t2l-gron.png";
    icon.shadow = "";
    return(icon);
}
function stoppy_icon()
{
    icon = new GIcon();
    icon.iconSize = new GSize(20,20);
    icon.iconAnchor = new GPoint(14,18);
    icon.image = "images/t2l-rod.png";
    icon.shadow = "";
    return(icon);
}
function ring_icon()
{
    icon = new GIcon();
    icon.iconSize = new GSize(60,60);
    icon.iconAnchor = new GPoint(30,41);
    icon.image = "images/ring.png";
    icon.shadow = "";
    return(icon);
}


// Quick function createing a marker from variables.
function createMarker(point,id, mytitle, myicon)
{
    var marker = new GMarker(point, {icon: myicon, id: id, title: mytitle });
    GEvent.addListener(marker, "click", function() { klick_stopp(id,false);});
    return marker;
}    

function clear_old_titles()
{
    var b=gmap.getBounds();
    var sw=b.getSouthWest();
    var ne=b.getNorthEast();

    // Set bounds little bigger then screen
    var slat=sw.lat()-0.0500;
    var nlat=ne.lat()+0.0500;
    var wlng=sw.lng()-0.0500;
    var elng=ne.lng()+0.0500;
    console.info("Clearing out titles within lat: "+slat+","+nlat+" lng1: "+ wlng+","+elng);

    for(var i=0; i<titles.length; i++)
    {
	var title=titles[i];
    
	// Check if withing border
	if(title.lat > slat &&
	   title.lat < nlat &&
	   title.lng > wlng &&
	   title.lng < elng)
	    continue;

	console.info("Clearing title " + title.lat + " " + title.lng);
	// Else, start deleteing
	
	// remove the array
	title.delete_stopps();	
	titles.splice(i, 1);
	delete(title);
    }
    console.info("Titles left in memory: "+titles.length);
}

function clear_all_titles()
{
    console.info("Clearing all titles.. ");

    while(titles.length>0)
    {
	var title=titles.pop();
    	
	// remove the array
	title.delete_stopps();	
	delete(title);
    }
}

// This function will go and get flags, for area the map is showing, called as sub from hamta_stopp()
function go_hamta_stopp()
{
    if(gmap.getZoom()<13) // Smaller zoom then 13, dont even try.
	return;

    var b=gmap.getBounds();
    var sw=b.getSouthWest();
    var ne=b.getNorthEast();

    // Set bounds little bigger then screen
    var slat=sw.lat()-0.0400;
    var nlat=ne.lat()+0.0400;
    var wlng=sw.lng()-0.0400;
    var elng=ne.lng()+0.0400;
	
    var ilat=parseInt(slat)+1;
    var ilng=parseInt(wlng)+1;
	
    while(ilat>slat)
	ilat-=0.05;
    while(ilng>wlng)
	ilng-=0.05;
	    
	
    var plat;
    var plng;
    for(plat=ilat; plat<nlat; plat+=0.05) // Latitude steps i defaulted to 0.04
    {
	if(plat>slat)
	{
	    for(plng=ilng;plng<elng;plng+=0.05) // Longitude steps is defaulted to 0.04
	    {
	        if(plng>wlng)
		{
		    if(hamta_stopp_in(plat, plng)<1)
			    return;
		}
	    }
	}
    }	
}
    

function hide_all()
{
    for(var i=0; i<titles.length; i++)
    {
	titles[i].hide_stopps();
    }
}
    
// This function will go and get flags, for area the map is showing.
function hamta_stopp()
{

    // Clear old stopps
    clear_old_titles();

    if(gmap.getZoom()<13) // Smaller zoom then 13, dont even try.
    {
	hide_all();
	return;
    }
    
    
    // Get new stopps
    go_hamta_stopp();
}


jwlTitle.prototype.lat=0;
jwlTitle.prototype.lng=0;
jwlTitle.prototype.data=0;
jwlTitle.prototype.stopps=null;
jwlTitle.prototype.show=0;
jwlTitle.prototype.working=0;
jwlTitle.prototype.drawed=0;
function jwlTitle(lat, lng)
{
    this.lat=lat;
    this.lng=lng;
    this.data=0;
    this.stopps=Array();
    this.show=0;
    this.working=0;
    this.drawed=0;
}
/**
 * Download stops is an expensive operation, therefore
 * we download one title, to the class, and then sets a short
 * timeout and competely returns, so the web browser has time
 * to reply for user request, or redrawing the screen in between.
 */
jwlTitle.prototype.get_stopps= function()
{
    if(this.working>0)
	return;
    this.working=1;

    console.info("Downloading title " + this.lat + " " + this.lng);

    // Create a new request on every try
    var Stopp_Request = getXMLHTTPRequest();
    var query = "json4.php" + "?lat=" + this.lat + "&lng=" + this.lng + "&kontor_id=" + kontor_id;
    if(tt>0)
     query+= "&tt=" + tt;
    
    Stopp_Request.open("GET", query , true);
    
    var nthis = this;
    Stopp_Request.onreadystatechange = function()
    {
	if(!Stopp_Request)
	    return;
	if(Stopp_Request.readyState != 4)
	    return;
	    
	// okay, query done
	nthis.working=0;
	setTimeout ( "go_hamta_stopp()", 10 );
	
	if(Stopp_Request.status != 200)
	{
	    delete(Stopp_Request);
	    return;
	}
	if(!Stopp_Request.responseText)
	{
	    delete(Stopp_Request);
	    return;
	}
	if(Stopp_Request.responseText.length < 20)
	{
	    delete(Stopp_Request);
	    return;
	}
	
	nthis.data = eval('(' + Stopp_Request.responseText + ')');
	delete(Stopp_Request);
    }

    Stopp_Request.send(null);
}

/**
 * Drawing stops is also an expensive operation, therefore
 * we download one title, to the class, and then sets a short
 * timeout and competely returns, so the web browser has time
 * to reply for user request, or redrawing the screen in between.
 */
jwlTitle.prototype.draw_stopps=function()
{
    if(!this.data)
	return;
    if(!this.data.markers)
	return;

    console.info("Drawing title " + this.lat + " " + this.lng);

    try {
     while(this.data.markers.length>0)
     {
	// When drawed, the data is poped from the data array,
	// once drawed we dont need to save the data anymore.
	var row=this.data.markers.pop();
	
	// Strange but in ie...
	if(!row)
	    continue;
	    
	var marker=null;


	// If we got the matching stopp_id, we can redraw the ringmarker anyway.
	if(row.s == stopp_selected)
	{	
	    remove_ringmarker();
	    set_stopp_selected(row.s, row.l, row.o);
	}


	if(row.a>0)
	{
	    var title_r = row.t + " är redan besökt idag.";
	    marker = createMarker(new GLatLng(row.l, row.o), row.s, title_r, stoppy_icon());
	}
	else if(row.y>0)
	{
	    var title_k = row.t + " kommer att besökas idag.";
	    marker = createMarker(new GLatLng(row.l, row.o), row.s, title_k, stoppg_icon());
	}
	else
	{
	    marker = createMarker(new GLatLng(row.l, row.o), row.s, row.t, stopp_icon());
	}


	if(marker)
	{
	    this.stopps.push(marker);
	    gmap.addOverlay(marker);
	}
     }
    } catch(e) {}    
    // this.data shud be empty anyway
    delete(this.data);
    this.data=null;

    // Set flags
    this.show=1;
    this.drawed=1;

    
    // Schedule this script again, so we will draw/fetch next title.
    setTimeout ( "go_hamta_stopp()", 10 );
}


jwlTitle.prototype.delete_stopps=function()
{
    while(this.stopps.length>0)
    {
	var stopp = this.stopps.pop();
	gmap.removeOverlay(stopp);	
	GEvent.clearInstanceListeners(stopp);
	delete(stopp);
    }
    delete(this.stopps);
    this.stopps=null;
}


jwlTitle.prototype.hide_stopps=function()
{
    for(var i = 0;i<this.stopps.length;i++)
    {
	this.stopps[i].hide();
    }
    this.show=0;
}

jwlTitle.prototype.show_stopps=function()
{
    for(var i = 0;i<this.stopps.length;i++)
    {
	this.stopps[i].show();
    }
    this.show=0;
}

// An array that remember all the fetched once so we makes no duplets.
function hamta_stopp_in(lat, lng)
{
    var lat2=lat.toPrecision(8);
    var lng2=lng.toPrecision(8);

    for(var i=0; i<titles.length; i++)
    {
	var title=titles[i];
	if(title.lat==lat2 && title.lng==lng2)
	{
	    if(title.show < 1)
	    {
		if(title.drawed<1)
		{
		    title.draw_stopps();
		    return(0);
		}
		if(title.show<1)
		{
		    title.show_stopps();
		}
	    }
	    return(1);
	}
    }
    

    var new_title= new jwlTitle(lat2, lng2);
    titles.push(new_title);
    new_title.get_stopps();    
    return(0);
}

// This function will zoom in on lat/lng and also set marker on stopp_selected
function zooma(st_lat, st_lng)
{
    if(gmap.getZoom()<13)
    {
	gmap.setZoom(15);
    }
    gmap.setCenter(new GLatLng(st_lat,st_lng));
}

function set_stopp_selected(stopp_id, st_lat, st_lng)
{
    remove_ringmarker();
    stopp_selected=stopp_id;
    ring_marker = createMarker(new GLatLng(st_lat,st_lng), stopp_id, "", ring_icon());
    gmap.addOverlay(ring_marker);
    zooma(st_lat, st_lng);
}

// Call this function to hide selected marker
function clear_stopp_selected()
{
    stopp_selected=0;
    remove_ringmarker();
}

function remove_ringmarker()
{
    if(ring_marker)
    {
	gmap.removeOverlay(ring_marker);	
	delete(ring_marker);
	ring_marker=null;
    }
}
