﻿/**Function used to determine the starting point of the bases.

This function garuntees that 3 bases will be formed.  
It first tries to set their location based on a LocalSearch for pizza, hospital, or car.  
If those don't return results (or the results are too far away), it searchs for a nearby streeview location.  
If that doesn't work it just places them near the map center.
**/

HSEngine.prototype.executeLocalSearch = function(baseKey){
	this.localSearch.setSearchCompleteCallback(this, function(){
		//Process results
		if (this.localSearch.results && this.localSearch.results.length > 0 && this.map.getCenter().distanceFrom(new GLatLng(this.localSearch.results[0].lat, this.localSearch.results[0].lng)) < 2000) {
            //Take the first result and add a base
            var result = this.localSearch.results[0];
			//$.data(window,'blueBase',result);
            this.bases[baseKey].init(new GLatLng(result.lat, result.lng), result.title);
            GEvent.addListener(this.bases[baseKey], "click", function(latlng) { this.openInfoWindowHtml(this.getTitle()); });
            this.map.addOverlay(this.bases[baseKey].marker);
            this.smallMap.addOverlay(this.bases[baseKey].smallMarker);

            //Setup next search
            this.localSearch.clearResults();
            this.localSearch.setCenterPoint(new GLatLng(this.map.getCenter().lat(), this.map.getCenter().lng() - .005));
    	} else {
			var me = this;
            //Otherwise call streetview to get a nearby street
            this.streetView.getNearestPanoramaLatLng(this.map.getCenter().addLng(0.006 * Math.random()),
            function(result) {
                if (result) {
                    me.bases[baseKey].init(result, baseKey);
                    GEvent.addListener(me.bases[baseKey].marker, "click", function(latlng) { this.openInfoWindowHtml("Blue Base"); });
                    me.map.addOverlay(me.bases[baseKey].marker);
                    me.smallMap.addOverlay(me.bases[baseKey].smallMarker);
                }
                else {
                    me.bases[baseKey].init(me.map.getCenter().addLng(0.006 * Math.random()), baseKey);
                    GEvent.addListener(me.bases[baseKey], "click", function(latlng) { this.openInfoWindowHtml("Blue Base"); });
                    me.map.addOverlay(me.bases[baseKey].marker);
                    me.smallMap.addOverlay(me.bases[baseKey].smallMarker);
                }
             });
        }
		
		if (baseKey == "blue")
			this.executeLocalSearch("green");
		else if (baseKey == "green") 
			this.executeLocalSearch("teal");
	 	else this.onBasesLoaded();
	});
	
	this.localSearch.execute(this.bases[baseKey].constructor.localSearch);
}


HSEngine.prototype.onBasesLoaded = function(){
    //Clear the local search object for good
    this.localSearch = null;
    //Creat the first wave to start the game
    this.curWave = Wave.getWaveById(1, this);
}
