
  var ge;
  var photoData;
  //var groundOverlay;
  
  google.load("earth", "1");

  function astrodemo_init() {
    google.earth.createInstance('map3d', initCB, failureCB);
	request = 'http://query.yahooapis.com/v1/public/yql?q=select%20farm%2C%20server%2C%20id%2C%20secret%2C%20title%2C%20owner.username%2C%20urls.url.content%2C%20tags.tag.raw%20from%20flickr.photos.info%20where%20(tags.tag.raw%20like%20\'astro%3A%25\')%20and%20photo_id%20in%20(select%20id%20from%20flickr.photos.search(30)%20where%20group_id%3D\'973956%40N23\'%20and%20machine_tags%3D\'astro%3ARA%3D\')&format=json&callback=parseYqlData';
	aObj = new JSONscriptRequest(request);
	aObj.buildScriptTag();
	aObj.addScriptTag();


  }
  
  function initCB(instance) {
    ge = instance;
    ge.getWindow().setVisibility(true);

	ge.getOptions().setMapType(ge.MAP_TYPE_SKY);

    
    // add a navigation control
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
	//experiment - can we load constellations from barnabu.co.uk?
	addKMLFromUrl('http://admin.nmm.ac.uk/js/constellation-boundaries.kmz');
	//addKMLFromUrl('http://admin.nmm.ac.uk/js/constellation-names.kmz');
	//addKMLFromUrl('http://admin.nmm.ac.uk/js/constellation-figures.kmz');
	
	

    
  }
  
  function failureCB(errorCode) {
  }
  
  function addKMLFromUrl(kmlUrl) {
      var link = ge.createLink('');
      link.setHref(kmlUrl);

      var networkLink = ge.createNetworkLink('');
      networkLink.setLink(link);
      networkLink.setFlyToView(true);

      ge.getFeatures().appendChild(networkLink);
    } 
  
	function selectPhoto(id) {
		var photo = photoData[id];
		//console.log(photo);
		if (typeof photo.fov == 'undefined') {
			photo.fov = {};
			photo.fov.x = photo.fov.y = 3.00;
		}
		showSky(photo);
		
		

		
	}
  function showSky(photo) {
    
      ge.getOptions().setMapType(ge.MAP_TYPE_SKY);
	  var oldFlyToSpeed = ge.getOptions().getFlyToSpeed();
      ge.getOptions().setFlyToSpeed(.2);  // Slow down the camera flyTo speed.
      var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
      	   lat = parseFloat(photo.Dec);
	       long = parseFloat(photo.RA - 180);
	       beta = Math.max(photo.fov.x,photo.fov.y) * 6.28/360;
	       range = 6378000 *(1.1917536 * Math.sin(beta/2) - Math.cos(beta/2) + 1);
		   rotation = 180-parseFloat(photo.orientation);
		   //orientation = orientation - 180;
	       lookAt.set(lat, long, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, rotation, 0, 2*range);
	
      ge.getView().setAbstractView(lookAt);
      ge.getOptions().setFlyToSpeed(oldFlyToSpeed);

	  	var groundOverlay = ge.createGroundOverlay('');
		groundOverlay.setIcon(ge.createIcon(''));
		
		groundOverlay.getIcon().setHref(photo.imgroot+'.jpg');
		var colour = groundOverlay.getColor();
		colour.set('99ffffff');
		groundOverlay.setLatLonBox(ge.createLatLonBox(''));
		
		var latField = photo.fov.y;
		//console.log(latField);
		var longField = photo.fov.x/Math.cos(lat*6.28/360);
		//console.log(longField);

		var north = lat + latField/2;
		var south = lat - latField/2;
		var east = long + longField/2;
		var west = long - longField/2;
		
		var latLonBox = groundOverlay.getLatLonBox();
		latLonBox.setBox(north, south, east, west, rotation);
		
		/*var pm = ge.createPlacemark('');
		var point = ge.createPoint('');
		point.setLatitude(lat);
		point.setLongitude(long);
		pm.setGeometry(point);
		
		var style = ge.createStyle('');
		pm.setStyleSelector(style);
		var icon = ge.createIcon('');
		icon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
		style.getIconStyle().setIcon(icon);

		pm.setName(photo.title);
		pm.setDescription('<a href="'+photo.url+'"><img src="'+photo.imgroot+'_m.jpg"></a><br>by <a href="'+photo.url+'">'+photo.username+'</a>');
		
		ge.getFeatures().appendChild(pm);*/
		ge.getFeatures().appendChild(groundOverlay);
		
  }
  

  function parseYqlData(data) {
	
	var tag; 
	var tmp;
	var photo;
	var id;
	var o = {};
	
	var photos = data.query.results.photo;
	/* Walk through the returned data and build an associative array of
	photos, o, keyed on photo id. (yeah, I know JavaScript doesn't really use
	associative arrays).*/
	for (p=0;p<photos.length;p++) {
		photo = photos[p];
		id = photo.id;
		
		if (typeof o[id] == 'undefined') { 
			o[id] = {};
			o[id]['name'] = [];
		}
		o[id]['title']=photo.title;
		o[id]['url'] = photo.urls.url;
		o[id]['username'] = photo.owner.username;
		o[id]['imgroot'] = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+id+'_'+photo.secret;
		tag = photo.tags.tag.raw;
		//split machine tag name and value
		tmp = tag.split('=');
		//discard namespace from tag name by splitting tmp[0] on :
		// store data as o[predicate] = value eg. o[id].RA = 85.123456
		var tagname = tmp[0].split(':')[1];
		if (tagname == 'name') {
			o[id]['name'].push(tmp[1]);
		} else {
			o[id][tagname] = tmp[1];
		}
		//fieldsize is a string in degrees, arcminutes or arcseconds.
		//We will standardise on a value in degrees.
		if (tmp[0] == 'astro:fieldsize') {
			//convert fieldsize string into a numeric value in degrees, using the width of the photo.
			tmp = o[id].fieldsize.split(' ');
			o[id].fov = {};
			o[id].fov.x = parseFloat(tmp[0]);
			o[id].fov.y = parseFloat(tmp[2]);
			if (tmp[3] == 'arcminutes') {
				o[id].fov.x = o[id].fov.x/60;
				o[id].fov.y = o[id].fov.y/60;
			}
			if (tmp[3] == 'arcseconds') {
				o[id].fov.x = o[id].fov.x/3600;
				o[id].fov.y = o[id].fov.y/3600;
			}
		}
	}
	
	photoData = o;
	buildController();
}

function buildController() {
	var controller = document.getElementById('controller');
	var html = '<ul>';
	var ids = [];

	//Generate buttons to control the image gallery - one per image.
	for (id in photoData) {
		var photo = photoData[id];
		ids.push(id);
		html = html+'<li><input type="image" onclick="selectPhoto('+id+');" src="'+photo.imgroot+'_s.jpg" alt="'+photo.title+'"> by <a href="'+photo.url+'">'+photo.username+'</a></li>';
	}
	html = html+'</ul>';
	controller.innerHTML = html;

}

// jsr_class.js
//
// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//
//
// Sample Usage:
//
// <script type="text/javascript" src="jsr_class.js"></script>
// 
// function callbackfunc(jsonData) {
//      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude + 
//            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
//      aObj.removeScriptTag();
// }
//
// request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&
//            output=json&callback=callbackfunc&location=78704';
// aObj = new JSONscriptRequest(request);
// aObj.buildScriptTag();
// aObj.addScriptTag();
//
//


// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementById("yqlquery");
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

