
/**
 * EarthGL.Topo defines the topography of the earth
 * @param {Integer} width width of topography
 * @param {Integer} height height of topography
 * @param {Number} hmin minimum depth
 * @param {Number} hmax maximum depth
 * @param {String/EarthGL.Layer} URL of a gray-scaled image representing
 * the topography. 
 * @constructor
 */

EarthGL.Topo = EarthGL.Class({
	topoData: null,
	layer: null,

	initialize: function(width,height,hmin,hmax,url) {
	    this.width = width;
	    this.height = height;
	    this.hmin = hmin;
	    this.hmax = hmax;
	    this.url = null;
	    this.layer = null;

	    if (typeof url == 'string') {
		this.url = url;
	    }
	    else {
		this.layer = url;
	    }

	    this.a = this.hmin;
	    this.b = (this.hmax-this.hmin)/255;

	},

	getURL: function(newParams,onready) {
	    var url; 

	    if (this.url) {
		return this.url;
	    }
	    else if (this.layer) {
		var p = {width: this.width, height: this.height};
		p = EarthGL.Util.merge(p,newParams);
		url = this.layer.getFullRequestString(p);
		//alert(url);
	    } 
	    else {
		url = '../images/topo_' + this.width + 'x' + this.height + '.png';
	    }

	    return url;
	},

	load: function(newParams,onready,lon,lat) {
	    var that = this;

	    if (0) {
	    this.topoCanvas = document.createElement("canvas");
	    //document.body.appendChild(topoCanvas);
	    this.topoCanvas.width = this.width;
	    this.topoCanvas.height = this.height;
	    this.topoContext = this.topoCanvas.getContext("2d");

	    var fun = function(onready) {
		return function() {
		    that.topoContext.drawImage(img,0,0);
		    that.topoData = that.topoContext.getImageData(0, 0, that.width, that.height);

		    if (onready) {
			//console.log('earth loaded');
			onready();
		    }	
		};
	    }(onready);


	    var img = new Image();
	    img.onload = fun;
	    img.src = this.getURL(newParams);
	    }

	    else {
		this.ti = new EarthGL.TileImages(this.width,this.height,this.layer);
		this.ti.events.register('loaded',null,function (ti) { 
			that.topoData = ti.data();

			if (onready) {
			    onready();
			}	
		    });
		
		var lon = lon || [-180, 180];
		var lat = lat || [-90,90];
		this.ti.draw(lon,lat);
	    }
	},


	scale: function(scale) {
	    this.a = this.hmin/scale;
	    this.b = (this.hmax-this.hmin)/(255*scale);
	},

	data: function(i,j) {
	    var h;
	    var data = this.topoData;

	    if (data) {	
		// TODO: cyclic
		i = Math.max(Math.min(i,data.width-1),0);
		j = Math.max(Math.min(j,data.height-1),0);
	
		h = this.a + this.b * data.data[j * (data.width*4) + i*4];
		h = Math.min(0,h);		    
	    }
	
	    return h;
	}

    });




