// index.js
/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * @fileoverview This is the main JavaScript file for the Driving Simulator
 * @author Roman Nurik
 * @supported Tested in IE6+ and FF2+
 *
 * Modified by GMaps Gaier for the Gaiagi Driver 
 *
 *   http://www.gaiagi.com/driving-simulator/
 *
 */

/**
 * The global Directions object for the currently loaded directions
 * @type {google.maps.Directions}
 */
var DS_directions = null;

/**
 * The list of driving steps loaded from google.maps.Directions
 * @type {Array.<Object>}
 */
var DS_steps = [];

/**
 * The list of path vertices and their metadata for the driving directions
 * @type {Array.<Object>}
 */
var DS_path = []; // entire driving path

/**
 * The global simulator instance that conducts the driving simulation
 * @type {DDSimulator}
 */
var DS_simulator; // instance of the DDSimulator class

/**
 * The car marker that appears on the reference map to the right of the main
 * simulation screen
 * @type {google.maps.Marker}
 */
var DS_mapMarker = null; // car marker on the Map

/**
 * Instead of using the plugin's built-in ID system, which doesn't like when
 * IDs are reused, we will use a separate dictionary mapping ID to placemark
 * object
 * @type {Object}
 */
var DS_placemarks = {};

/**
 * The callback for when the 'Go!' button is pressed. This uses the Maps API's
 * Directions class to get the route and pull out the individual route steps
 * into a path, which is rendered as a polyline.
 */
function DS_goDirections() {
  $('#route-details').empty();
  show_route_details();
  $('#route-details').html(
      '<span class="loading">Loading directions...</span>');
  
  DS_directions = new google.maps.Directions(DS_map, null);
  
  google.maps.Event.addListener(DS_directions, 'load', DS_directionsLoaded);
  
  google.maps.Event.addListener(DS_directions, 'error', function() {
    $('#route-details').empty();
    show_route_details();
    $('#route-details').html(
        '<span class="error">No directions found.</span>');
  });
  
  DS_directions.load('from: ' + $('#from').val() + ' to: ' + $('#to').val(),
      {getSteps: true, getPolyline: true});

  pageTracker._trackEvent('Driver', 'Directions',$('#from').val() + ' -- ' + $('#to').val());	
}

/**
 * Initialization after directions are loaded
 */
function DS_directionsLoaded() {
  // Directions data has loaded
  $('#route-details').empty();
  show_route_details();
  var route = DS_directions.getRoute(0);
  var start = route.getStartGeocode();
  var end = route.getEndGeocode();
  
  // build the path and step arrays from the google.maps.Directions route
  DS_buildPathStepArrays();
  
  DS_geHelpers.clearFeatures();
  if (g_webcamLink && g_conf_arr['ge_webcams']) {
      DS_ge.getFeatures().appendChild(g_webcamLink);
      // DS_ge.getFeatures().appendChild(g_weatherLink);
  }
  if (centerOverlay && g_conf_arr['show_center']) {
      DS_ge.getFeatures().appendChild(centerOverlay);
  }

  DS_placemarks = {};
  
  // create the starting point placemark
  DS_placemarks['start'] = DS_geHelpers.createPointPlacemark(
      new google.maps.LatLng(start.Point.coordinates[1],
                             start.Point.coordinates[0]),
      {description: start.address, standardIcon: 'grn-diamond'});
  
  // create the point placemarks for each step in the driving directions
  for (var i = 0; i < DS_steps.length; i++) {
    var step = DS_steps[i];
    
    var placemark = DS_geHelpers.createPointPlacemark(
        step.loc, {description: step.desc, standardIcon: 'red-circle'});
    
    DS_placemarks['step-' + i] = placemark; 
    
    google.earth.addEventListener(placemark, 'click', function() {
      // match up the placemark to its id in the dictionary to find out
      // which step number it is
      var id = '';
      for (k in DS_placemarks)
        if (DS_placemarks[k] == this)
          id = k;
      
      var stepNum = parseInt(id.match(/step-(\d+)/)[1]);
      
      DS_flyToStep(stepNum);
    });
  }
  
  // create the ending point placemark
  DS_placemarks['end'] = DS_geHelpers.createPointPlacemark(
      new google.maps.LatLng(end.Point.coordinates[1],
                             end.Point.coordinates[0]),
      {description: end.address, standardIcon: 'grn-diamond'});
  
  // build the route LineString; instead of creating a LineString using
  // pushLatLngAlt, which has some performance issues, we will construct a
  // KML blob and use parseKml() 
  var lineStringKml = '<LineString><coordinates>\n';
  
  for (var i = 0; i < DS_path.length; i++)
    lineStringKml +=
        DS_path[i].loc.lng().toString() + ',' +
        DS_path[i].loc.lat().toString() +
        ',10\n';
  
  lineStringKml += '</coordinates></LineString>';
  
  // create the route placemark from the LineString KML blob
  var routeLineString = DS_ge.parseKml(lineStringKml);
  routeLineString.setTessellate(true);
  
  var routePlacemark = DS_ge.createPlacemark('');
  routePlacemark.setGeometry(routeLineString);
  DS_placemarks['route'] = routePlacemark;
  
  routePlacemark.setStyleSelector(
      DS_geHelpers.createLineStyle({width: 10, color: '88ff0000'}));
  
  DS_ge.getFeatures().appendChild(routePlacemark);

  // build the left directions list
  DS_buildDirectionsList();
  
  // fly to the start of the route
  DS_flyToLatLng(new google.maps.LatLng(
                 start.Point.coordinates[1], start.Point.coordinates[0]));
  
  // enable the simulator controls
  $('#simulator-form input').removeAttr('disabled');
  $('#driver_fieldset').fadeIn('1000');
  // $('#butt_start').css("background-color", "gold");
  
  // destroy the simulator if exists
  if (DS_simulator) {
    DS_simulator.destroy();
    DS_simulator = null;
  }
  $('#butt_start').val("Start");

}

/**
 * Generates the DS_path and DS_step arrays from the global DS_directions
 * instance
 * 
 * NOTE: only the first route is used
 */
function DS_buildPathStepArrays() {
  // begin processing the directions' steps and path
  DS_steps = [];
  DS_path = [];
  
  var polyline = DS_directions.getPolyline();
  var route = DS_directions.getRoute(0);
  var numPolylineVertices = polyline.getVertexCount();
  var numSteps = route.getNumSteps();
  
  for (var i = 0; i < numSteps; i++) {
    var step = route.getStep(i);
    
    var firstPolylineIndex = step.getPolylineIndex();
    
    var lastPolylineIndex = -1;
    if (i == numSteps - 1)
      lastPolylineIndex = numPolylineVertices - 1;
    else {
      // subtract 2 because the last vertex of a step is duplicated
      // as the first vertex of the next step in google.maps.Directions results
      lastPolylineIndex = route.getStep(i + 1).getPolylineIndex() - 2;
    }
    
    DS_steps.push({
      loc: step.getLatLng(),
      desc: step.getDescriptionHtml(),
      distanceHtml: step.getDistance().html,
      pathIndex: DS_path.length
    });
    
    var stepDistance = step.getDistance().meters;
    for (var j = firstPolylineIndex; j <= lastPolylineIndex; j++) {
      var loc = polyline.getVertex(j);
      var distance = (j == numPolylineVertices - 1) ?
                     0 : DS_geHelpers.distance(loc, polyline.getVertex(j + 1));
      
      DS_path.push({
        loc: loc,
        step: i,
        distance: distance,
        
        // this segment's time duration is proportional to its length in
        // relation to the length of the step
        duration: step.getDuration().seconds * distance / stepDistance
      });
    }
  }
}

/**
 * Generates the HTML elements for the left directions list
 * 
 * NOTE: only the first route is used
 */
function DS_buildDirectionsList() {
  var start = DS_directions.getRoute(0).getStartGeocode();
  var end = DS_directions.getRoute(0).getEndGeocode();
  
  $('#route-details').append($(
      '<div id="dir-start">' + start.address + '</div>'));
  
  $('#route-details').append('<ol>');
  for (var i = 0; i < DS_steps.length; i++) {
    $('#route-details ol').append($(
        '<li class="dir-step" id="dir-step-' + i + '">' +
        DS_steps[i].desc +
        '<div class="note">' + DS_steps[i].distanceHtml + '</div>' + 
        '</li>'));
  }
  
  $('#route-details').append($(
      '<div id="dir-end">' + end.address + '</div>'));
  
  // handle events on the directions list
  $('#dir-start').click(function() {
    DS_flyToLatLng(new google.maps.LatLng(
                   start.Point.coordinates[1], start.Point.coordinates[0]));
  });
  
  $('#dir-end').click(function() {
    DS_flyToLatLng(new google.maps.LatLng(
                   end.Point.coordinates[1], end.Point.coordinates[0]));
  });
  
  $('#route-details li').click(function() {
    var id = $(this).attr('id');
    if (id == 'dir-start' || id == 'dir-end')
      return;
    
    var stepNum = parseInt(id.match(/dir-step-(\d+)/)[1]);
    DS_flyToStep(stepNum);
  });
}

/**
 * Fly the camera to the given step index in the route, and highlight it in
 * the directions list
 * @param {number} stepNum The 0-based step index to fly to
 */
function DS_flyToStep(stepNum) {
  var step = DS_steps[stepNum];
  
  var la = DS_ge.createLookAt('');
  la.set(step.loc.lat(), step.loc.lng(),
      0, // altitude
      DS_ge.ALTITUDE_RELATIVE_TO_GROUND,
      DS_geHelpers.getHeading(step.loc, DS_path[step.pathIndex + 1].loc),
      60, // tilt
      50 // range (inverse of zoom)
      );
  DS_ge.getView().setAbstractView(la);
  
  DS_highlightStep(stepNum);

  // $("div.demo").scrollTop(300);
  // p.offset();

  DS_map.panTo(step.loc);
  SyncViews_gloc(step.loc);

}

/**
 * Highlights the given step in the left directions list
 * @param {number} stepNum The 0-based step index to highlight in the
 *     directions list
 */
function DS_highlightStep(stepNum) {
  $('#route-details li').removeClass('sel');
  $('#route-details #dir-step-' + stepNum).addClass('sel');
}

/**
 * Move the camera to the given location, staring straight down, and unhighlight
 * all items in the left directions list
 * @param {google.maps.LatLng} loc The location to fly the camera to
 */
function DS_flyToLatLng(loc) {
    if (DS_ge) {
	var la = DS_ge.createLookAt('');
	la.set(loc.lat(), loc.lng(),
	       10, // altitude
	       DS_ge.ALTITUDE_RELATIVE_TO_GROUND,
	       90, // heading
	       0, // tilt
	       200 // range (inverse of zoom)
	       );
	DS_ge.getView().setAbstractView(la);
    }
    
    $('#route-details li').removeClass('sel');
    
    SyncViews_gloc(loc);

}

/**
 * Formats a time given in seconds to a human readable format
 * @param {number} s Time in seconds
 * @return {string} A string formatted in hh:mm form representing the given
 *     number of seconds
 */
function DS_formatTime(s) {
  var m = Math.floor(s / 60);
  s %= 60;
  var h = Math.floor(m / 60);
  m %= 60;
  s = Math.round(s);
  return ((h < 10) ? ('0' + h) : h) + ':' + ((m < 10) ? ('0' + m) : m);
}

/**
 * Simulator controls
 * @param {string} command The control command to run
 * @param {Function?} opt_cb Optional callback to run when the command
 *     completes its task
 */
function DS_controlSimulator(command, opt_cb) {
  switch (command) {
    case 'reset':
      if (DS_simulator)
        DS_simulator.destroy();
      
      // create a DDSimulator object for the current DS_path array
      // on the DS_ge Earth instance
      DS_simulator = new DDSimulator(DS_ge, DS_path, {
        // as the simulator runs, reposition the map on the right and the
        // car marker on the map, and update the status box on the bottom
        on_tick: function() {
          DS_map.panTo(DS_simulator.currentLoc);
          DS_mapMarker.setLatLng(DS_simulator.currentLoc);
          
          if (DS_simulator) {
            $('#status').html(
                '<strong>Time:</strong> ' +
                  DS_formatTime(DS_simulator.totalTime) + '<br/>' +
                '<strong>Distance:</strong> ' +
                  (Math.round(
                      DS_simulator.totalDistance / 1609.344 * 10) / 10) +
                  ' mi' + '<br/>' +
                '<strong>Current Speed:</strong> ' +
                  Math.round(DS_simulator.currentSpeed / 0.44704) + 'mph') +
                  '<br/>';
          }
        },
        
        // when the simulator moves to a new step (specified as an integer
        // index in DS_path items), highlight that step in the directions
        // list
        on_changeStep: function(stepNum) {
          DS_highlightStep(stepNum);
        }
      });
      
      if (!DS_mapMarker) {
        // create vehicle location indicator on map
        var icon = new google.maps.Icon();
        icon.iconSize = new google.maps.Size(42, 42);
        icon.iconAnchor = new google.maps.Point(21, 21);
        icon.image = 'smart_marker.png';
        DS_mapMarker = new google.maps.Marker(
                       DS_simulator.currentLoc, {icon: icon});
        DS_map.addOverlay(DS_mapMarker);
      }
      
      DS_map.setZoom(13);
      DS_mapMarker.setLatLng(DS_simulator.currentLoc);
      
      DS_updateSpeedIndicator();
      DS_simulator.initUI(opt_cb);

      // reset birds view
      // bmap.SetMapMode(VEMapMode.Mode2D);
      simulator_add_heading = 0;
      $('#butt_start').val("Start");

      break;
    
    case 'start':
      $('#butt_start').css("background-color", "");
      if (!DS_simulator)
        DS_controlSimulator('reset', function() {
          DS_simulator.start();
          if (opt_cb) opt_cb();
        });
      else {
        DS_simulator.start();
        if (opt_cb) opt_cb();
      }
      break;
    
    case 'pause':
      if (DS_simulator)
        DS_simulator.stop();

      $('#butt_start').val("Resume");
      
      if (opt_cb) opt_cb();
      break;
    
    case 'resume':
      if (DS_simulator)
        DS_simulator.start();
      
      if (opt_cb) opt_cb();
      break;
    
    case 'slower':
      if (DS_simulator && DS_simulator.options.speed > 0.125) {
        DS_simulator.options.speed /= 2.0;
        DS_updateSpeedIndicator();
      }
      break;
    
    case 'faster':
      if (DS_simulator && DS_simulator.options.speed < 32.0) {
        DS_simulator.options.speed *= 2.0;
	// alert("speed " + DS_simulator.options.speed);
        DS_updateSpeedIndicator();
      }
      break;
  }
}

/**
 * Update the speed indicator in the simulation controls box to reflect
 * the current simulation speed multiplier
 */
function DS_updateSpeedIndicator() {
  if (DS_simulator.options.speed < 1)
    $('#speed-indicator').text('1/' +
        Math.floor(1 / DS_simulator.options.speed) + 'x');
  else
    $('#speed-indicator').text(Math.floor(DS_simulator.options.speed) + 'x');
}

function _doFold(id, delay) {
    if (!g_loaded) return;

    // $("#placeholder").toggle();
    // alert(" fold ");
    // $("#"+id).toggle("fold", {size: 15 }, 800); 
    if (!delay) {
	delay = 800;
    }
    // $("#"+id).toggle("blind", {direction: "vertical" }, 800); 
    $("#"+id).slideToggle("fast");

    hide_birds();
}

var g_hide_birds_save_top = 0;

// parseFloat(top.replace("px", "")) < clientHeight) {

function hide_birds(yes) {

    try {
	// top=$('#birdv1').css("top");
	top = document.getElementById("birdv1").style.top;
    } catch (err) {}

    var clientHeight = document.documentElement.clientHeight;

    // alert (clientHeight + " " + top );

    // var top=$('#birdv1').position().top;
    if (g_hide_birds_save_top == 0 || yes) {
	n_top = clientHeight + "px";
	// alert ("top = 0 " + clientHeight + " " + top + " " + n_top);
	// $('#birdv1').css("top", n_top);
	if (navigator.userAgent.match("MSIE")) {
	    try {
		// document.getElementById("birdv1").style.top = n_top;
		setTimeout('document.getElementById("birdv1").style.top = "'+n_top+'"', 300);  
	    } catch (err) {}
	} else {
	    $('#birdv1').css("top", n_top);
	}
	if (g_hide_birds_save_top == 0) {
	    g_hide_birds_save_top=top;
	}
    } else {
	n_top = g_hide_birds_save_top ;
	// alert ("back " + clientHeight + " " + top + " " + String(n_top));
	// $('#birdv1').css("top", n_top);
	try {
	    document.getElementById("birdv1").style.top = n_top;
	} catch (err) {}
	g_hide_birds_save_top = 0;
    }
}

    
function _undoFold(id) {
    // $("#"+id).toggle("fold", {size: 15 }, 800); 
    $("#"+id).toggle("blind", {direction: "vertical" }, 800); 

    // $("#placeholder").hide();
}


// Used with mouse move
function SyncViews(kmlEventorLookAt) {

    lat = 0;
    try {
	head = kmlEventorLookAt.getHeading();
	la = kmlEventorLookAt;
	// alert ("1 " + la);
    } catch (Error) {
    	la = DS_ge.getView().copyAsLookAt(DS_ge.ALTITUDE_RELATIVE_TO_GROUND);
	// alert ("2 " + la);
    };
    
    lat = la.getLatitude();
    lng = la.getLongitude();
    curHeading = la.getHeading();
    
    // pos GMap
    Gp = new GLatLng(lat, lng);
    
    // this.currentLoc = Gp;
    
    // alert(Gp);
    DS_map.panTo(Gp);
    // DS_map.setCenter(Gp, 17);
    
    //
    // alert(myPano);
    if (!myPano) {
	// svClient = new GStreetviewClient();
	myPano = new GStreetviewPanorama(document.getElementById("strv1"));
	GEvent.addListener(myPano, "initialized", function(loc) {
	    debug("streetv init..ed");
	    return;
        });
	GEvent.addListener(myPano, "error", function(errorCode) {
	    // alert ("The requested panorama could not be displayed");
	    if (errorCode == 603) {
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	    }
	});
	
    }
    
    // alert(Gp);
    myPOV = {yaw:curHeading,pitch:0};
    myPano.setLocationAndPOV(Gp, myPOV);
    
    // pos BirdV
    // p = new VELatLong(kmlEvent.getLatitude(), kmlEvent.getLongitude());
    p = new VELatLong(lat, lng);
    
    // bmap.PanToLatLong(p);
    // bmap.SetBirdseyeScene(p);
    
    if (curHeading >= 315 || curHeading < 45) {
	// bmap.SetBirdseyeOrientation(VEOrientation.North);
	bmap.SetBirdseyeScene(p,VEOrientation.North)
	    dir = "north";
    }
    if (curHeading < 135 && curHeading >= 45) {
	// bmap.SetBirdseyeOrientation(VEOrientation.East);
	bmap.SetBirdseyeScene(p,VEOrientation.East)
	    dir = "east";
    }
    if (curHeading < 225 && curHeading >= 135) {
	// bmap.SetBirdseyeOrientation(VEOrientation.South);
	bmap.SetBirdseyeScene(p,VEOrientation.South)
	    dir = "south";
    }
    if (curHeading < 315 && curHeading >= 225) {
	// bmap.SetBirdseyeOrientation(VEOrientation.West);
	bmap.SetBirdseyeScene(p,VEOrientation.West)
	    dir = "west";
    }
    
    // alert("curHeading " + curHeading + " " + dir);
    
    // set link
    set_linkto();

    // show location 
    show_location(Gp);
}


// used by init of driving
function SyncViews_gloc(loc, ctrl_earth) {

    // pos GMap
    Gp = loc;
    
    // this.currentLoc = Gp;
    
    // DS_map.panTo(Gp);
    // DS_map.setCenter(Gp, 17);
    
    //
    if (!myPano) {
	// svClient = new GStreetviewClient();
	myPano = new GStreetviewPanorama(document.getElementById("strv1"));
	GEvent.addListener(myPano, "initialized", function(loc) {
	    debug("streetv init..ed");
	    return;
        });
	GEvent.addListener(myPano, "error", function(errorCode) {
	    // alert ("The requested panorama could not be displayed");
	    if (errorCode == 603) {
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	    }
	});
	
  }
    
    if (DS_ge) {
	la = DS_ge.getView().copyAsLookAt(DS_ge.ALTITUDE_RELATIVE_TO_GROUND);
	var curHeading = la.getHeading();
    }
    if (ctrl_earth) {
	la.setLatitude(loc.lat());
	la.setLongitude(loc.lng());
	DS_ge.getView().setAbstractView(la);
    }
    
    // alert("heading "  + curHeading);
    if (!curHeading) {
	curHeading = 90;
    }
    
    myPOV = {yaw:curHeading,pitch:0};
    myPano.setLocationAndPOV(Gp, myPOV);
    
    // pos BirdV
    vep = new VELatLong(loc.lat(), loc.lng());
    p=vep;
    
    if (curHeading >= 315 || curHeading < 45) {
	// bmap.SetBirdseyeOrientation(VEOrientation.North);
	bmap.SetBirdseyeScene(p,VEOrientation.North)
	    dir = "north";
    }
    if (curHeading < 135 && curHeading >= 45) {
	// bmap.SetBirdseyeOrientation(VEOrientation.East);
	bmap.SetBirdseyeScene(p,VEOrientation.East)
	    dir = "east";
    }
    if (curHeading < 225 && curHeading >= 135) {
	// bmap.SetBirdseyeOrientation(VEOrientation.South);
	bmap.SetBirdseyeScene(p,VEOrientation.South)
	    dir = "south";
    }
    if (curHeading < 315 && curHeading >= 225) {
	// bmap.SetBirdseyeOrientation(VEOrientation.West);
	bmap.SetBirdseyeScene(p,VEOrientation.West)
	    dir = "west";
    }
    
    // alert("pan to " + vep);
    // bmap.PanToLatLong(vep);
    // bmap.SetCenterAndZoom(vep, 13);
    // bmap.SetBirdseyeScene(vep);

    g_currentLoc = loc;
}

var g_result_address ;

function show_location (loc) {

    if (! g_showlocation) {
	var g_showlocation = new GClientGeocoder();
    }
    g_showlocation.getLocations(loc, function(addresses) {
	if(addresses.Status.code != 200) {
	    // alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
	    // no data
	} else { 
	    var result = addresses.Placemark[0];
	    str = '<fieldset style="font-size: 85%; color: #fbfbfb; background: #5f5f5f url(\'graphs/bg.png\') repeat-x scroll;">';
    	    str += '<legend><b>Location Information</b></legend>';
	    // str += '<ul style="margin-left: -2em;" ><li>' + result.address ;
	    str += '<li style="margin-left: 12px;">' + result.address ;
	    g_result_address = result.address;
	    // str += '<li style="margin-left: 12px;"> <a href="#" style="display: inline;" onclick="show_loc_info(\'tweets\');" id="show_tweets">Show local Twitter Tweets</a><img height="12" id="tweet_wait" style="background-color: white; display: none; margin-left: 3px; " src="wait-rot.gif" /> </li>';

	    ///str += '<li> <input style="display: inline;" type="submit" onclick="show_zestimate();" id="show_zestimate" value="Show ZEstimate House Value"/></li>';
	    if (navigator.userAgent) {
		var s = navigator.userAgent;
		if (s.match("gmapsg")) {
		    // get_zestimate(result);
		    // var t = str.match("gmapsg");
		    // alert(t);
		     str += '<li style="margin-left: 12px;"> <a href="#" style="display: inline;" onclick="show_loc_info(\'zestimate\');" id="show_zestimate">Show Zestimate<sup>&copy;</sup> Home Value</a><img height="12" id="zest_wait" style="background-color: white; display: none; margin-left: 3px; " src="wait-rot.gif" /> </li>';
		}
	    }

	    // <br/> <br/>
	    str += '</li><li style="margin-left: 12px;">(Lat, Long): <br/>' + loc  ;
	    str += '</li><li style="margin-left: 12px;">Copy this location to directions: <a href="javascript: set_dir(\'from\',\''+loc+'\')">From</a>, <a href="javascript: set_dir(\'to\',\''+loc+'\')">To</a></li>';
	    str += ' <input style="display: block; margin-top: 15px;" type="submit" onclick="show_route_details();" id="showlocclose" value="Close Location Information"/>';
            str += "    </fieldset>";
	    
	    // alert (str);
	    $('#location-details').html(str);
	    $('#location-details').css("display", "block");
	    // $('#location-details').show();
	    $('#route-details').css("display", "none");


	}
    });
}

function set_dir(which,loc) {
    loc=String(loc);
    loc=loc.substr(1, loc.length-2);
    $('#'+which).val(loc);
}

function show_route_details() {
    $('#route-details').css("display", "block");
    $('#location-details').css("display", "none");
    g_result_address = null;
}

function get_location(nofold) {

    if (!DS_ge) {
	setTimeout("get_location("+nofold+")", 500);
	return;
    }

    //if (!window.geocodeLocation) {
    // window.geocodeLocation = 'City name, country, latitude and longitude, etc';
    //}
    // window.geocodeLocation = prompt('Enter a location', window.geocodeLocation);

    // reset clear func
    $('#get_location').attr("onFocus", "");

    str = $('#get_location').val();
    if (str.match("lookat")) {
	arr = str.split(":");
	var lookAt = DS_ge.createLookAt('');
	// alert(arr + " " + arr[1]);
	lookAt.set(Number(arr[1]), Number(arr[2]), Number(arr[6]), 
		   DS_ge.ALTITUDE_RELATIVE_TO_GROUND, 
		   Number(arr[5]), Number(arr[4]), Number(arr[3]));
	// lookAt.set(Number(arr[1]), Number(arr[2]), 10, 		   DS_ge.ALTITUDE_RELATIVE_TO_GROUND, 		   0, 0, 1500);
	
	DS_ge.getView().setAbstractView(lookAt);
	SyncViews(lookAt);
	set_linkto(lookAt);
    } else {
	var geocoder = new google.maps.ClientGeocoder();
	// alert(str);
	// http://www.seeing-stars.com/Live/StarsAddresses_P.shtml
	geocoder.getLatLng(str, function(point) {
	    if (point) {
		if (DS_ge) {
		    var lookAt = DS_ge.createLookAt('');
		    lookAt.set(point.y, point.x, 10, 
			       DS_ge.ALTITUDE_RELATIVE_TO_GROUND, 
			       0, 0, 1500);
		    DS_ge.getView().setAbstractView(lookAt);
		}
		DS_map.panTo(point);
		SyncViews_gloc(point);
		// set link
		set_linkto(lookAt);
		$('#route-details').empty();
		$('#simulator-form input').attr('disabled', 'disabled');
		// $('#goto_status').html("");
		// $('#goto_status').css("background-color", "");
		// $('#menu_goto').css("background-color", "");
	    } else {
		// $('#goto_status').show();
		// $('#goto_status').html("Could not resolve the address ...");
		// $('#goto_status').css("background-color", "#928728");
		// _undoFold("goto"); 
		// hide_birds();
		// $('#menu_goto').css("background-color", "#922828");
	    }
	});
    }

    if (!nofold) {
	_undoFold("goto");
    }
}

function init_conf() {
    // init street overlay
    g_conf_arr['streetv_overlay'] = 0;
    // init radio
    g_conf_arr['radio'] = 0;  

    // alert(g_conf_arr + " YX " + g_conf_arr['traffic'] );

    for (conf in g_conf_arr) {
	t_conf="toggle_" + conf;
	// alert(conf + " " + t_conf + " ");
	if (g_conf_arr[conf]) {
	    document.getElementById(t_conf).checked=true;
	} else {
	    document.getElementById(t_conf).checked=false;
	}
    }

    $("#streetv_refresh_rate").val("1.0");
    gtilt = 80;
    $("#ge_tilt").val(gtilt);
    grange = 10;
    $("#ge_range").val(grange);

    document.getElementById("tr_smart").checked=true;
    
    if (navigator.userAgent) {
	var str = navigator.userAgent;
	if (str.match("gmapsg")) {
	    // setTimeout("get_tweets()", 5000);
	}
    }

    // done here as jquery+ui is loaded via google loader
    $.getScript("ui.slider.js", function(){
	// $('#car_size_slider').slider({ min: 1 });
	$('#car_size_slider').slider({max: 10});
	$('#car_size_slider').slider('option', 'step', 0.1);
	// $('#car_size_slider').slider('option', 'min', 1.0);

	// $('#car_size_slider').bind('slidechange', function(ev, ui) {
	$('#car_size_slider').bind('slide', function(ev, ui) {

	    val = $("#car_size_slider").slider('value');
	    
	    sc = model_car.getScale();
	    sc.set(val,val,val);
	    model_car.setScale(sc);
	    
	    $("#car_size_str").html('Car size factor is ' + val + '.');

	});

	$('#menu_tweet_id').draggable();

    });


}

g_openclose_config = 0; // close
g_save_radio_top = 0;

function openclose_config(open) {
    // open = 1  : open

    if (open == 1 || g_openclose_config == 1) {
	// move radio away
	g_save_radio_top = $("#conf_radio").css("top");
	$("#conf_radio").css("top", "-300px");
	g_openclose_config = 0; // now closed
    } else {
	if (g_save_radio_top) {
	    $("#conf_radio").css("top", g_save_radio_top);
	}
	g_openclose_config = 1; // now open
    }
}


function conf_handler(command, opt_cb) {
    switch (command) {
    case 'ge_roads':
	if (g_conf_arr[command]) {
	    DS_ge.getLayerRoot().enableLayerById(DS_ge.LAYER_ROADS, false);
	    g_conf_arr[command] = 0;
	} else {
	    DS_ge.getLayerRoot().enableLayerById(DS_ge.LAYER_ROADS, true);
	    g_conf_arr[command] = 1;
	}
	break;
	
    case 'ge_buildings':
	if (g_conf_arr[command]) {
	    DS_ge.getLayerRoot().enableLayerById(DS_ge.LAYER_BUILDINGS, false);
	    g_conf_arr[command] = 0;
	} else {
	    DS_ge.getLayerRoot().enableLayerById(DS_ge.LAYER_BUILDINGS, true);
	    g_conf_arr[command] = 1;
	}
	break;
	
    case 'ge_webcams':
	if (g_conf_arr[command]) {
	    DS_ge.getFeatures().removeChild(g_webcamLink);
	    g_conf_arr[command] = 0;
	} else {
	    DS_ge.getFeatures().appendChild(g_webcamLink);
	    g_conf_arr[command] = 1;
	}
	break;
	
    case 'show_center':
	if (g_conf_arr[command]) {
	    DS_ge.getFeatures().removeChild(centerOverlay);
	    g_conf_arr[command] = 0;
	} else {
	    DS_ge.getFeatures().appendChild(centerOverlay);
	    g_conf_arr[command] = 1;
	}
	break;
	
    case 'traffic':
	traff_overl = g_store_arr['traffic'];
	if (g_conf_arr[command]) {
	    traff_overl.hide();
	    g_conf_arr[command] = 0;
	} else {
	    traff_overl.show();
	    g_conf_arr[command] = 1;
	}
	break;
    case 'streetv_overlay':
	streetv_overlay = g_store_arr['streetv_overlay'];
	if (!streetv_overlay ) {
	    streetv_overlay = new GStreetviewOverlay();
	    g_store_arr['streetv_overlay'] = streetv_overlay;
	    g_conf_arr[command] = 0;
	}
	if (g_conf_arr[command]) {
	    DS_map.removeOverlay(streetv_overlay);
	    g_conf_arr[command] = 0;
	} else {
	    DS_map.addOverlay(streetv_overlay);
	    g_conf_arr[command] = 1;
	}
	break;

    case 'pan_layer':
	layer = g_store_arr[command];
	if (!layer) {
	    layer = new GLayer("com.panoramio.all");
	    // pan_layer.hide();
	    DS_map.addOverlay(layer);
	    g_store_arr[command] = layer;
	    g_conf_arr[command] = 0;
	}
	if (g_conf_arr[command]) {
	    layer.hide();
	    g_conf_arr[command] = 0;
	} else {
	    layer.show();
	    g_conf_arr[command] = 1;
	}
	break;

	
    case 'wikipedia_en_layer':
	layer = g_store_arr[command];
	if (!layer) {
	    layer = new GLayer("org.wikipedia.en");
	    // pan_layer.hide();
	    DS_map.addOverlay(layer);
	    g_store_arr[command] = layer;
	    g_conf_arr[command] = 0;
	}
	if (g_conf_arr[command]) {
	    layer.hide();
	    g_conf_arr[command] = 0;
	} else {
	    layer.show();
	    g_conf_arr[command] = 1;
	}
	break;


    case 'resize':
	// $('#route-details, #earth-container, #map-container').each(function() {
	$('#route-details, #map-container').each(function() {
	    $(this).resizable();
	});
	break;

  }
}

function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
	return "";
    else
	return results[1];
}

var g_streetv_refresh_rate = 1.0;

function set_streetv_refresh_rate()
{
    g_streetv_refresh_rate = $('#streetv_refresh_rate').val();
    // alert(g_streetv_refresh_rate);
}

function set_ge_tilt()
{
    gtilt = Number($('#ge_tilt').val());
    // alert(gtilt);
}
function set_ge_range()
{
    grange = Number($('#ge_range').val());
    // alert(gtilt);
}

function set_linkto(lookAt)
{
    // alert(DS_ge);
    if (!lookAt) {
        lookAt = DS_ge.getView().copyAsLookAt(DS_ge.ALTITUDE_RELATIVE_TO_GROUND);
    }
    // alert(lookAt);
    str = "lookat:" + lookAt.getLatitude() + ":" +	lookAt.getLongitude() + ":" +	lookAt.getRange()+ ":" + lookAt.getTilt()+ ":" + lookAt.getHeading() + ":" +lookAt.getAltitude();
    u_str=encodeURI(str);
    url = window.location.href;
    p = url.indexOf("?");
    if (p >= 0) {
	url=url.substr(0, p);
    }
    link = url + "?goto=" + u_str;
    // alert(str + " XX " + u_str + " XX "  + link);
    // alert(link);
    document.getElementById('linkto').innerHTML=link;
    $("#menu_linkto").attr("href",link);
    
    // window.clipboardData.setData('Text',x);
}

var tours = new Array();

// tours['Rome'] = ["Piazza di San Giovanni in Laterano, 00184 Rome, Italy", 	 "Piazza Pio XII, 00193 Rome, Italy"];
// tours['Rome_Coll'] = ["Via Labicana, 123, 00184 Rome, Italy", 
// 		      "Via del Corso, 00186 Rome, Italy"];
// tours['Rome_Coll'] = ["Via Celio Vibenna, 00184 Rome, Italy", 
// 		      "Via del Corso, 00186 Rome, Italy"];

tours['LasVegas_Strip'] = ["36.08103202245626, -115.17254496724203",
		     "36.12132085326543, -115.17184944672648", 80, 20];

tours['SanFran_GoldenG'] = ["37.78425111432667, -122.40776932205307",
		     "37.83242334026777, -122.4800308708255"];

tours['NYC_BroadWash'] = ["40.70347421279834, -74.01444254055448",
		     "40.730818118937634, -73.9976581845339", 70, 15];
tours['NYC_Manhattan'] = ["40.77258822545935, -73.97850212220527",
			  "40.75113049229677, -73.98761615305295", 70, 10];

tours['Yellowst_OldFaith'] = ["44.45756592215072, -110.82702215965769",
			  "43.47956103373383, -110.76220466809372", 80,25];

tours['Sydney_RBG'] = ["-33.87665862130953, 151.20950383961033",
		       "-33.86039100436096, 151.21500544067766", 70,20];

tours['Rome_Coll'] = ["41.888399025348896, 12.490293105904655", 
		      "41.895873323812076, 12.482210224906497", 70,20];
tours['Rome_StPeter'] = ["41.89618239143567, 12.481984000037428", 
		      "41.90224770909521, 12.458481867951548", 70,20];

tours['London_Buck'] = ["51.50607656568169, -0.11780726566800583", 
		      "51.4998710776753, -0.14186677843090933", 75, 25];

tours['Paris_NotreD'] = ["48.85674233830997, 2.2901677652449024", 
		      "48.853750528660875, 2.3483101466450336", 75, 25];
tours['Paris_LaDef'] = ["48.87217801053316, 2.300045254870909", 
		     "48.89144651247034, 2.2406073846286603", 75, 25];

 


function set_tour(tour)
{
    start = tours[tour][0];
    end = tours[tour][1];
    // alert (start  + " XX " + end + " XX " + tours[tour]);
    $('#from').attr("value",start);
    $('#to').attr("value",end);

    v = tours[tour][2];
    // alert("X"+v+"x");
    if (v) {
	gtilt = Number(v);
	$("#ge_tilt").val(v);
    }
    v = tours[tour][3];
    if (v) {
	grange = Number(v);
	$("#ge_range").val(v);
    }

    // prepare the tour link
    set_tour_url();

    _doFold("tour");
    // hide_birds();
    DS_goDirections();
    // $.get("info.txt?t="+tour);
    pageTracker._trackEvent('Tour', tour);
}

function set_tour_url()
{
    str="?from=" + $('#from').val() + "&to=" + $('#to').val() + "&gtilt=" + gtilt + "&grange=" + grange;
    u_str=encodeURI(str);
    url = window.location.href;
    p = url.indexOf("?");
    if (p >= 0) {
	url=url.substr(0, p);
    }
    link = url + u_str;
    // alert(str + " XX " + u_str + " XX "  + link);
    // alert(link);
    $('#tour_link').html('<a href="'+link+'">Link</a> to share the present tour:<br/>' + link);
    $('#tour_link').show();

    // window.clipboardData.setData('Text',x);
}

function submit_tour_recomm()
{
    str="?from=" + $('#from').val() + "&to=" + $('#to').val() + "&gtilt=" + gtilt + "&grange=" + grange + "&recomm=" + $('#tour_recomm_text').val();
    $.get("info.txt"+encodeURI(str));

    pageTracker._trackEvent('Tour', 'RECOMMEND', str);

    $('#tour_recommend').toggle('blind', {direction: 'vertical' }, 333);
}

var g_celebs;

function open_holly()
{
    if (!g_celebs) {
	$.get("celeb.txt", function(data){

	    g_celebs = data.split("\n");

	    // alert("Data Loaded:\n " + data);
	    // alert("Data Loaded:\n " + res[0] + " XX " + res[1]);

	    f = Math.round(Math.random() * g_celebs.length);
	    t = Math.round(Math.random() * g_celebs.length);

	    // alert (f + " x " + t + " X " + g_celebs[f]);

	    $('#holly_text_f').html(g_celebs[f]);
	    $('#holly_text_t').html(g_celebs[t]);
	    $('#holly_details').show();
	    $('#t_set_holly').show();
	    $('#holly_wrap').css("border", "1px solid #eee");

	    $('#t_holly').attr("value", "Hollywood Celebrities (click again for new tour)");
	});
    } else {

	f = Math.round(Math.random() * g_celebs.length);
	t = Math.round(Math.random() * g_celebs.length);
	
	// alert (f + " x " + t + " X " + g_celebs[f]);
	
	$('#holly_text_f').html(g_celebs[f]);
	$('#holly_text_t').html(g_celebs[t]);
	$('#holly_details').show();
    }

    $('#celeb_info').hide();
}

function set_holly()
{
    f = $('#holly_text_f').html().split(",");
    // alert(f[1] + " x " +f[2]);
    t = $('#holly_text_t').html().split(",");

    $('#from').attr("value",f[1]+","+f[2]);
    $('#to').attr("value",t[1]+","+t[2]);

    // prepare the tour link
    set_tour_url();

    _doFold("tour");
    // hide_birds();
    DS_goDirections();
    str="?f=" + f +"&t=" + t;
    // $.get("info.txt"+encodeURI(str));
    pageTracker._trackEvent('Tour', 'Celebs', str);

}
//
// car changer
//
var g_car_kmz_item = 0;
var g_car_scale = 1.3;
var g_old_car_heading ;
var g_car_type;
var g_model;
var g_modelplacemark;

function get_car(type, ah, car_kmz_item, car_scale) {
    MODEL_URL = 'http://www.gaiagi.com/driving-simulator/kml/' + type;
    g_car_type = type;
    g_old_car_heading = simulator_add_heading;
    simulator_add_heading = ah;
    g_car_scale = car_scale;
    g_car_kmz_item = car_kmz_item;
    window.google.earth.fetchKml(
      DS_ge,
      MODEL_URL,
      function(obj) {
        get_car_cb(obj);
      });
    pageTracker._trackEvent('Driver', 'Car', type);
}
function get_car_cb(obj) {
    if (DS_simulator && DS_simulator.model) {
	model = DS_simulator.model;
	lat = model.getLocation().getLatitude();
	lng = model.getLocation().getLongitude();
	alt = model.getLocation().getAltitude();
	head = model.getOrientation().getHeading();
	modelPlacemark = DS_simulator.modelPlacemark;
	DS_ge.getFeatures().removeChild(modelPlacemark);    
    }

    kml = obj.getFeatures().getChildNodes().item(g_car_kmz_item);
    modelPlacemark_car = kml;
    model_car = modelPlacemark_car.getGeometry();
    model_car.setAltitudeMode(DS_ge.ALTITUDE_RELATIVE_TO_GROUND);
    // model_car.setAltitudeMode(DS_ge.ALTITUDE_ABSOLUTE);
    DS_ge.getFeatures().appendChild(modelPlacemark_car);
    sc = model_car.getScale();
    s = g_car_scale;
    sc.set(s,s,s);
    model_car.setScale(sc);
    if (lat) {
	model_car.getLocation().setLatLngAlt(lat, lng, alt);
	model_car.getOrientation().setHeading(head + simulator_add_heading + g_old_car_heading);
	// model_car.getOrientation().setHeading(head);
    }
    if (DS_simulator) {
	// alert(model_car);
	DS_simulator.model =  model_car;
	DS_simulator.modelPlacemark = modelPlacemark_car;
    }
    g_model = model_car;
    g_modelplacemark = modelPlacemark_car;
}


/*
 * Zillow estimate for location
 *
 */
// http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1c9k97844qz_43hp8&address=1022+Palisades+Beach+Rd&citystatezip=Santa%20Monica,%20CA

function get_zestimate(res_addr) {
    // adminarea = res.AddressDetails.Country.AdministrativeArea;
    // if (adminarea.SubAdministrativeArea) {
    //subadminarea = adminarea.SubAdministrativeArea;
    //	sub_areaname= subadminarea.SubAdministrativeAreaName;
    //} else {
    //	sub_areaname = "";
    //}

    $('#zest_wait').show();

    addr_arr = res_addr.split(",");
    par = "address=" + encodeURIComponent(addr_arr[0].replace(/-[0-9]+/, "")) + "&citystatezip=" + encodeURIComponent(addr_arr[1])  +",%20"+ encodeURIComponent(addr_arr[2]);
    // str = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1c9k97844qz_43hp8&" + par + '&output=json&callback=?';
    // str = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1c9k97844qz_43hp8&" + par + '&output=json';
    par = encodeURIComponent(par);
    str = 'generic-proxy.php?url='+encodeURIComponent("http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1c9k97844qz_43hp8&" + par);
    // alert(str);
    $.get(str, function(xml, textstatus){
     	// alert(textstatus + " " + xml);
	code = $(xml).find('code').text();
	inf_str = '<div style="margin-top: 15px; margin-left: 15px; font-size: 150%;"><a href="http://www.zillow.com" target="_blank"><img height="45" border="0" style="float: right; margin-top: 12px; margin-left: 9px; background-color: white;" src="http://www.zillow.com/vstatic/c00b584370fd35b72b29f44affd2d885/static/images/logo.gif" /></a> Zestimate<sup>&copy;</sup> for home <u>near</u> <br/>"' + res_addr + '"</div><hr/>';
	if (code == 0) {
	    $(xml).find('result').each(function(){
		res = $(this);
		street = $(res).find('street').text();
		zipcode = $(res).find('zipcode').text();
		lat = $(res).find('latitude').text();
		lng = $(res).find('longitude').text();
		zestimate = $(res).find('amount').text();
		valch = $(res).find('valueChange').text();
		last_upd = $(res).find('last-updated').text();
		// alert(lat + " " + lng + " " + zestimate + " " + xml);
		// inf_str += lat + " " + lng + " " + zestimate;

		inf_str += '<div style="margin-left: 15px; margin-top: 15px; font-size: 130%;">Zestimate<sup>&copy;</sup>: &nbsp;&nbsp;&nbsp;<b>$' + $(res).find('amount').text() + '</b>&nbsp;&nbsp;&nbsp; (last update: '+last_upd+')<p/>';
		inf_str += 'Value change of $' + $(res).find('valueChange').text() + ' over the last 30 days ('+ Math.round(valch/zestimate*100) +'%) <p/>';
		inf_str += 'Address of home zestimated<sup>&copy;</sup>: ' + $(res).find('street').text() + ', ' + $(res).find('city').text() + ', ' + $(res).find('state').text() + ', ' + $(res).find('zipcode').text() + '<p/>';
		inf_str += 'More details: <a target="_blank" href="' + $(res).find('homedetails').text() + '">Home Details</a>';
		inf_str += ', <a target="_blank" href="' + $(res).find('graphsanddata').text() + '">Home Value Chart</a><p/>';
		inf_str += 'Data provided by <a target="_blank" href="http://www.zillow.com">zillow.com</a></div><p/><hr/>';

	    });

	    $("#location_details").html(inf_str);

	    show_loc_info_fin();
	    
	} else {
	    if (code != 508) {
		alert (code);
	    }
	}

	$('#zest_wait').hide();

    });
 
}

/*
 * Wrapper for Loc infos
 *
 */

function show_loc_info(type) {
    switch (type) {
    case "tweets": 
	get_tweets();
	break;
    case "zestimate":
	get_zestimate(g_result_address);
	break;
    }

}


/*
 * Local Twitter Tweets 
 *
 */

// http://search.twitter.com/search.json?geocode=40.757929%2C-73.985506%2C2mi&rpp=15&callback=?
// http://apiwiki.twitter.com/Twitter-Search-API-Method:-search

function get_tweets() {

    ctr = DS_map.getCenter();
    lat = ctr.lat();
    lng = ctr.lng();
    radius = "7mi";
    
    // &since=2009-04-21

    nr = 50;
    str = 'http://search.twitter.com/search.json?geocode='+ encodeURIComponent(lat+','+lng+','+radius)+'&rpp=' + nr + '&callback=?';
    // alert(str);
    $('#tweet_wait').show();
    $.getJSON(str, 
	      function(data)
        {
	    len = data.results.length;
	    if (! g_result_address) {
		area_str = "Local Tweets";
	    } else {
		area_str = 'Tweets around "' + g_result_address + '"';
	    }
	    // alert("res " + len + " " + navigator.userAgent);
	    inf_str = '<h3><a href="http://www.twitter.com" target="_blank"><img border="0" style="margin-right: 6px;" height="30" src="http://assets0.twitter.com/images/twitter_logo_header.png" alt="Twitter"/></a>'+area_str+' </h3>';
	    // var msie = navigator.userAgent.match("MSIE") ? 1 : 0;;
	    // msie = 0;
	    $.each(data.results, function(i, tweet){
		loc_arr = {};
		if (i < 3) {
		    // alert(tweet.text + "\n " + tweet.location);
		}
		loc = tweet.location.replace(/.*: */,"");
		loc_split = loc.split(",");
		backc = i%2 == 1 ? '#555555' : '#333333';
		paddop = i == 0 ? "6px" : "18px";
		inf_str += '<a style="" border="0" href="http://twitter.com/' + tweet.from_user + '" target="_blank"><img border="0" style="margin-top: 0px; padding-top: '+paddop+'; float: right ;" height="30" src="' + tweet.profile_image_url + '"/></a>';
		inf_str += '<div style="padding-left: 6px; background-color: '+backc+'; padding-top: 9px; padding-bottom: 9px; display: block; border-bottom: 1px outset #ffffff">' + tweet.text + '<div style="font-size: 85%"><i>Location: ' + tweet.location + '; User: <a href="http://twitter.com/' + tweet.from_user + '" target="_blank">' + tweet.from_user + '</a>; Created: '+tweet.created_at.replace("+0000", "(GMT)")+'</i></div></div>';
		// from '+tweet.source+'</div>';
		// debug(inf_str);
		if (0 && ! loc_arr[loc]) {

		    loc_arr[loc] = 1;

		    placemark = DS_ge.createPlacemark(''); 
		    
		    var point = DS_ge.createPoint(''); 
		    point.setLatitude(parseFloat(loc_split[0])); 
		    point.setLongitude(parseFloat(loc_split[1])); 
		    //point.setLatitude(37.59); 
		    //point.setLongitude(-122.234); 
		    placemark.setGeometry(point); 
		    DS_ge.getFeatures().appendChild(placemark); 
		    
		    var balloon = DS_ge.createHtmlDivBalloon('');
		    balloon.setMaxWidth(300);
		    balloon.setFeature(placemark);
		    
		    var div = document.createElement('DIV');
		    div.innerHTML = tweet.text + '<br/>'
			+ 'User: ' + tweet.from_user 
			+ '<img src="'+tweet.profile_image_url + '">';
		    balloon.setContentDiv(div);
		    
		    DS_ge.setBalloon(balloon);

		    google.earth.addEventListener(placemark, 
						  'click', 
						  function(event) {
			var text = inf_str;
			event.preventDefault(); 
			setTimeout(function() {
			    alert(text + "\nXX:" 
				  + event.getTarget().getParentNode().getId()
				  + "\nYY:" + event.getTarget().getType());
			}, 0);
		    });
		    
		} else {
		    // debug("found loc " + loc);
		}

	    });

	    $("#location_details").html(inf_str);

	    show_loc_info_fin();

	    pageTracker._trackEvent('Local Info', 'Tweets', g_result_address);

	    // $("#location_details_close1").draggable();
	    // $("#location_details_wrapper").draggable();

	    // DS_ge.getWindow().setVisibility(false);
	    // g_strv_top = $('#strv1').css("top");
	    // g_ge_top = $('#earth-container').css("top");
	    // alert (g_strv_top + " " + g_ge_top);

	    // $('#strv1').css("top", "-1000px");
	    // $('#earth-container').css("top", "-1000px");

	    //if (len <= 0) {
	    //	setTimeout("get_tweets()", 25000);
	    //}

	});
   
}

function show_loc_info_fin() {
    var clientHeight = document.documentElement.clientHeight;
    $("#location_details").css("height", Math.round(clientHeight * 0.42) + "px");
    $("#location_details_wrapper").fadeIn('3600');

    $('#tweet_wait').hide(); 
    
    hide_birds(1);
}


var g_radio_started = 0;
function start_radio () {

    // alert ("radio ...");
    if (! g_radio_started) {
	$('#radio_iframe2').attr("src", "http://www.labpixies.com/campaigns/radio/radio.html");
	g_radio_started = 1;
    }
}

function RIP(res) {

    req = $.ajax({   type: "GET",
			 url: str, 
			       async: false,
			 dataType: "script",
			 success: 
    function(req_obj, textstatus){
	alert("SUCC " + req_obj + " " + textstatus);
    },
			 dataFilter: 
    function(req_obj, textstatus){
	alert("datafil " + req_obj + " " + textstatus);
    },
			 error: 
    function(req_obj, textstatus, errorThrown){
	alert("error " + req_obj + " " + textstatus + " " + errorThrown);
    }
			 });

// Virtual earth stuff
//    http://msdn.microsoft.com/en-us/library/bb429619.aspx    

    var pixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());
    
    info += "LatLongToPixel: " + pixel.x + ", " + pixel.y + "\n";
    
    // Check to see if the current birdseye view contains the pushpin pixel point.
    info += "contains pixel " + pinPixel.x + ", " + pinPixel.y + ": " + 
	be.ContainsPixel(pinPixel.x, pinPixel.y, map.GetZoomLevel()) + "\n";
    
    // Check to see if the current view contains the pushpin LatLong.
    info += "contains latlong " + pinPoint + ": " + be.ContainsLatLong(pinPoint) + "\n";
    
    // This method may return null, depending on the selected view and map style.
    info += "latlong: " + map.PixelToLatLong(pixel);
    
}



