<!--

var Ts = '';
var Map_script = '/cgi-bin/map.pl?';
var XML_script = '/cgi-bin/map_xml_data.pl?';
var TSt_script = '/cgi-bin/ts_table.pl?';
var ref_map_src = '/images/explorer/world_elev_index_map.png';
var m_Data1,mapExtent;
var mx,my,wx,wy,bx,by;
var drop_margin = 10;

/////////////////////////////////////////////////////////////////
/*
*
*	Mouse Events Block
*
*/
/////////////////////////////////////////////////////////////////

var Map_coord,Map_size;

var Agent = navigator.userAgent.toLowerCase();
var Aname = navigator.appName.toLowerCase();
var Os = navigator.platform.toLowerCase();
var isWin = (Os.indexOf("win")!=-1);
var isMac = (Os.indexOf("mac")!=-1);
var isGec = (Agent.indexOf("gecko")!=-1);
var isExplorer = (Aname.indexOf("explorer")!=-1);
var Win = [0,0];
var Mac = (isMac && isExplorer) ? [9,14] : [0,0];
var isMacGec = (isMac && isGec);

/////////////////////////////////////////////////////////////////

function init()
{
  img_bg= document.images['map_bg'];
  img_wt= document.images['map_wait'];
  img_0 = document.images['map'];
  img_1 = document.images['reference_map'];

  div_0 = document.getElementById('map_layer');
  div_1 = document.getElementById('map_wait_layer');

  c_lon = document.getElementById('lon');
  c_lat = document.getElementById('lat');

  div_2 = document.getElementById('map_square_layer');
  if (isExplorer) div_2.style.filter="alpha(opacity=40)";
//  if (Aname == "konqueror") div_2.style.KhtmlOpacity='0.5';

  div_3 = document.getElementById('map_coords');

  m_Data1  = new dataObj('map_data1');
  mapExtent= new extentObj(Map_extent_full,[img_0.width,img_0.height]);
  Map_size = [img_0.width-1,img_0.height-1];

  Map_coord = find_xy(img_bg);
  Set_Map();

  img_0.onload     =map_loaded;
  div_2.onmousemove=Map_onmousemove;
  div_3.onmousemove=Map_onmousemove;
  div_0.onmouseover= function() {if (document.coord.float_box.checked) div_3.style.visibility = "visible";};
  div_0.onmousemove=Map_onmousemove;
  div_0.onmouseout =Map_onmouseout;
  div_0.onmouseup  =Map_onclick;
  div_0.onmousedown=img_Down;
  document.body.onmousemove=no_Map;
  window.onresize=Map_onresize;

  var Args = parseArgs(document.URL);
  var mSize= new Array(); mSize['640x480']=0; mSize['960x720']=1; mSize['1280x960']=2;

  if (Args['type']) Type = Args['type'];
  if (Args['date']) date = Args['date'];
  if (Args['extent']) mapExtent.extent = Args['extent'].split('_');
  if (Args['size']) document.map_size.size.selectedIndex = mSize[Args['size']];
  if (Args['towns']) document.info_layers.towns.checked = Number(Args['towns']) ? true : false;
  if (Args['roads']) document.info_layers.roads.checked = Number(Args['roads']) ? true : false;
  if (Args['lakes']) document.info_layers.lakes.checked = Number(Args['lakes']) ? true : false;
  if (Args['countries']) document.info_layers.countries.checked = Number(Args['countries']) ? true : false;

  Loading = true;
  if (Args['resample']) document.navigation.resample.selectedIndex = Number(Args['resample']);
  if (Args['shade']) document.navigation.shade.selectedIndex = Number(Args['shade']);
  Loading = false;

  map_resize(document.map_size.size,true);
  select_data(Type,(Args['resample'])?true:false);

/*  var Str = "Arguments-\n";
  for (var i=0; i<Args.length; i+=2)
  {
    Str += 'Key= '+Args[i]+'   Value= '+Args[i+1]+"\n";
  }
  alert(Str);*/
// http://nasademo.sr.unh.edu/maps/?type=airphoto_3f&extent=-71.11702331245651_42.927083333333364_-70.66469206680584_43.266331767571366&size=640x480&date=3000-01-01&towns=0&roads=0&countries=1&lakes=0&resample=0&shade=0
}

/////////////////////////////////////////////////////////////////

function find_xy(Img) {
  var Img_coord = new Array(2);
  Img_coord = [Img.offsetLeft+Mac[0]+Win[0], Img.offsetTop+Mac[1]+Win[1]];
  var tempElm = Img.offsetParent;

  while (tempElm != null) {
    Img_coord[0] += tempElm.offsetLeft;
    Img_coord[1] += tempElm.offsetTop;
    tempElm = tempElm.offsetParent || null;
  }

  return Img_coord;
}

/////////////////////////////////////////////////////////////////

function Set_Map() {
  div_0.style.left = Map_coord[0]+"px";
  div_0.style.top  = Map_coord[1]+"px";
  div_0.style.visibility = "visible";

  div_1.style.left = Map_coord[0]+"px";
  div_1.style.top  = Map_coord[1]+"px";
}

/////////////////////////////////////////////////////////////////

function no_Map (ev) {
  if (!Mouse_down) return false;

  if (!ev) var ev = window.event;

  bx = ev.pageX ? ev.pageX : ev.clientX + document.documentElement.scrollLeft;
  by = ev.pageY ? ev.pageY : ev.clientY + document.documentElement.scrollTop;

  bx -= Map_coord[0];
  by -= Map_coord[1];

	////////////////////

  if (Mouse_down) {
	// if outside the map
    if (bx<-drop_margin || by<-drop_margin || bx>Map_size[0]+drop_margin || by>Map_size[1]+drop_margin) {
      Mouse_down = false;
      if (Zoomin || Zoomout) { div_2.style.visibility = "hidden"; }
      if (Pan)    { wx=zx; wy=zy; drawPan(Map_size,Map_coord); }
    }
  }
  return false;
}

/////////////////////////////////////////////////////////////////

function Map_onmousemove(ev)
{
  if (Loading) return false;
  if (!ev) var ev = window.event;

  wx = ev.pageX ? ev.pageX : ev.clientX + document.documentElement.scrollLeft;
  wy = ev.pageY ? ev.pageY : ev.clientY + document.documentElement.scrollTop;

  mx = wx - Map_coord[0];
  my = wy - Map_coord[1];

	////////////////////

  var Coords = mapExtent.coords(mx,my,100);
  c_lon.innerHTML = Coords[0];
  c_lat.innerHTML = Coords[1];

  var dataStr = '';
  if (m_Data1.loaded) {
    var mc = Math.floor(my/Map_size[1]*m_Data1.nrows)*m_Data1.ncols+Math.floor(mx/Map_size[0]*m_Data1.ncols);
    dataStr = "&nbsp;" + ((mc<0 || mc>=m_Data1.data.length) ? '' : (m_Data1.data[mc]!=m_Data1.nodata) ?  (m_Data1.data[mc]+"&nbsp;"+m_Data1.units) : 'No Data');
    m_Data1.target.innerHTML = dataStr;
    dataStr = "<br />&nbsp;Data: " + dataStr + "&nbsp;";
  }

  if (document.coord.float_box.checked) {
    div_3.innerHTML = "&nbsp;Lon: " + Coords[0] + "&nbsp;<br />&nbsp;Lat: " + Coords[1] + "&nbsp;" + dataStr;
    div_3.style.left = (wx + 5)  + "px";
    div_3.style.top  = (wy - 35) + "px";
  }

	////////////////////

  if (Mouse_down) {
	// if inside the map
    if ((Zoomin || Zoomout) && (Math.abs(zx-mx)>10 || Math.abs(zy-my)>10))
	drawZoom(div_2,Map_size,Map_coord);
    if (Pan) drawPan(Map_size,Map_coord);
  }
  return false;
}

/////////////////////////////////////////////////////////////////

function Map_onmouseout() {
  c_lon.innerHTML = "&nbsp;";
  c_lat.innerHTML = "&nbsp;";
  if (m_Data1.loaded) m_Data1.target.innerHTML = "&nbsp;";

  div_3.style.visibility = "hidden";
  return false;
}

/////////////////////////////////////////////////////////////////

function Map_onclick() {
  if (Loading || !Mouse_down) return false;
  Mouse_down = false;
  var zoom = Zoom_factor;

  if (Zoomin || Zoomout) {
    if (Rect_zm[2]>10 || Rect_zm[3]>10) {
      if (!document.navigation.confirm.checked || confirm("Do you want zooming to the selected area?")) {
	mx = Rect_zm[0]-Map_coord[0]+Rect_zm[2]/2;
	my = Rect_zm[1]-Map_coord[1]+Rect_zm[3]/2;
	zoom = Math.min(Map_size[0]/Rect_zm[2],Map_size[1]/Rect_zm[3]);
      }
      else { div_2.style.visibility = "hidden"; return false; }
    }
    div_2.style.visibility = "hidden";
  }
  if (Pan) {
    if (Math.abs(wx-zx)>5 || Math.abs(wy-zy)>5) {
      mx = Map_size[0]/2 - (wx-zx);
      my = Map_size[1]/2 - (wy-zy);
    }
    wx = zx; wy = zy; drawPan(Map_size,Map_coord);
  }

  mapExtent.makeExtent(mx,my,zoom);
  load_map();

  return false;
}

/////////////////////////////////////////////////////////////////

function Map_onresize() {
  if (calc_status) Set_Calc_Img_Position();
}

//////////////////////////////////////////////////////////////////
//			Selection Tool				//
//////////////////////////////////////////////////////////////////
var zx,zy;
var Mouse_down=false;
var Rect_zm=Rect_pn=[0,0,0,0];

function img_Down(ev)
{
  if (Loading || Mouse_down) return false;
  Mouse_down = true;

  if (Zoomin || Zoomout) {
    zx = mx; zy = my;
    Rect_zm = [mx,my,1,1];
    drawZoom(div_2,Map_size,Map_coord);
  }
  else if (Pan) { zx = wx; zy = wy; }

  return false;
}

/////////////////////////////////////////////////////////////////

function drawZoom(sel_rect,M_size,M_coord) {
  if (mx<2 || my<2 || mx>M_size[0] || my>M_size[1]) return false;

  if (mx>zx) { Rect_zm[0] = M_coord[0]+zx-3; Rect_zm[2] = mx-zx-2; }
  else { Rect_zm[0] = M_coord[0]+mx+2; Rect_zm[2] = zx-mx-2; }
  if (my>zy) { Rect_zm[1] = M_coord[1]+zy-3; Rect_zm[3] = my-zy-2; }
  else { Rect_zm[1] = M_coord[1]+my+2; Rect_zm[3] = zy-my-2; }

  if (Rect_zm[2]>10 || Rect_zm[3]>10) {
    div_2.style.visibility = "visible";

    sel_rect.style.width   = Math.max(2,Rect_zm[2])+"px";
    sel_rect.style.height  = Math.max(2,Rect_zm[3])+"px";

    sel_rect.style.left = Rect_zm[0]+"px";
    sel_rect.style.top  = Rect_zm[1]+"px";
  }
  else {div_2.style.visibility = "hidden"; }

  return false;
}

/////////////////////////////////////////////////////////////////

function drawPan(M_size,M_coord) {
	// top right bottom left - css clip order
  Rect_pn[0] = wy>=zy?0:(zy-wy);
  Rect_pn[1] = wx>=zx?(M_size[0]+1-wx+zx):M_size[0]+3;
  Rect_pn[2] = wy>=zy?(M_size[1]+1-wy+zy):M_size[1]+3;
  Rect_pn[3] = wx>=zx?0:(zx-wx);

  div_0.style.clip = "rect("+Rect_pn[0]+"px,"+Rect_pn[1]+"px,"+Rect_pn[2]+"px,"+Rect_pn[3]+"px)";
  div_0.style.left = (M_coord[0]+M_size[0]+1-Rect_pn[1]-Rect_pn[3])+"px";
  div_0.style.top  = (M_coord[1]+M_size[1]+1-Rect_pn[2]-Rect_pn[0])+"px";

  return false;
}

//////////////////////////////////////////////////////////////////
/*
*
*	On image (map) load Block
*
*/
/////////////////////////////////////////////////////////////////
var Loading = false;

function map_loaded() {
  div_0.style.visibility = "visible";
  div_1.style.visibility = "hidden";
  Loading = false;

  document.images['reference_map'].src = ref_map_src;
}

//////////////////////////////////////////////////////////////////
/*
*
*	Page Block
*
*/
/////////////////////////////////////////////////////////////////

function map_resize(sel,l) {
  var lm   = l ? false : true;
  var Size = [[640,480],[960,720],[1280,960]][sel.selectedIndex];
  var Divs = [div_0,div_1];
  var Imgs = [img_bg,img_0,img_wt];

  for (var n=0; n<Divs.length; n++)
  {
    Divs[n].style.width = Size[0]+"px";
    Divs[n].style.height= Size[1]+"px";
  }
  for (var n=0; n<Imgs.length; n++)
  {
    Imgs[n].width = Size[0];
    Imgs[n].height= Size[1];
  }

  m_url_history = [];				/// Clear history
  m_history = -1;
  div_0.style.clip = "rect(0px,"+Number(img_0.width+3).toString()+"px,"+Number(img_0.height+3).toString()+"px,0px)";
  Map_size = [img_0.width-1,img_0.height-1];	/// Set map size
  mapExtent.setSize(img_0.width,img_0.height);
  if (lm) load_map();
}

/////////////////////////////////////////////////////////////////

function map_options() {
  var map_options_param =
	"&towns=" + (document.info_layers.towns.checked ? 1 : 0) +
	"&roads=" + (document.info_layers.roads.checked ? 1 : 0) +
	"&countries=" + (document.info_layers.countries.checked ? 1 : 0) +
	"&lakes=" + (document.info_layers.lakes.checked ? 1 : 0);
  return map_options_param;
}

/////////////////////////////////////////////////////////////////

function load_map() {
  if (Loading) return false;
  map_loading();
  date = get_map_date();

  if (!document.navigation.resample.selectedIndex) document.navigation.shade.selectedIndex = 0;
  var data_opt = "&resample=" + document.navigation.resample.selectedIndex + "&shade=" + document.navigation.shade.selectedIndex;

  img_0.src = Map_script + "type=" + Type + mapExtent.to_String(true) + "&date=" + date + map_options() + data_opt;
  ref_map_src = "/images/spool/ref_map_" + mapExtent.to_String(false) + ".png";
//  alert(img_0.src);

  m_url_history = m_url_history.slice(0,++m_history);
  push_history();

	/*	Update calculator map	*/
  if (calc_status) {
    document.images['calc_map_background'].src = Map_script + "type=none" + mapExtent.to_String(true).replace(/&size=\S+/,'') + map_options();
    Set_Calc_Img_Position();
  }
}

/////////////////////////////////////////////////////////////////

function get_map_date() {
  var Date;

  switch (Ts) {
    case 'daily':
      Date = document.date.year.options[document.date.year.selectedIndex].value + "-" + document.date.month.options[document.date.month.selectedIndex].value + "-" + document.date.day.options[document.date.day.selectedIndex].value; break;

    case 'monthly':
      Date = document.date.year.options[document.date.year.selectedIndex].value + "-" + document.date.month.options[document.date.month.selectedIndex].value + "-00"; break;

    case 'monthly_clim':
      Date = "0000-" + document.date.month.options[document.date.month.selectedIndex].value + "-00"; break;

    case 'yearly':
      Date = document.date.year.options[document.date.year.selectedIndex].value + "-00-00"; break;

    case 'decadal':
      Date = document.date.year.options[document.date.year.selectedIndex].value + "-00-00"; break;

    default:
      Date = '3000-01-01';
      break;
  }

  return Date;
}

/////////////////////////////////////////////////////////////////

function map_loading() {
  div_1.style.visibility = "visible";
  div_0.style.visibility = "hidden";
  Loading = true;
  m_Data1.clear(); stop_anim();
  return false;
}

/////////////////////////////////////////////////////////////////

function navigate(b0,b1,b2,b3) {
  if (Loading) return false;

  mapExtent.setExtent([b0,b1,b2,b3]);
  load_map();
}

/////////////////////////////////////////////////////////////////

function select_data(tpy,l) {
  var lm   = l ? false : true;
  if (Loading) return false;
  Type = tpy;
//  date = get_map_date();

  DownloadUrl(TSt_script+"type="+Type+"&date="+date, true, function(xmlDoc,responseCode) {
    var att_data = xmlDoc.getElementsByTagName('ts_table')[0];
	Ts =			att_data.getAttribute('time_series');
	Start_Year =		Number(att_data.getAttribute('start_year'));
	Start_Month_1 =		Number(att_data.getAttribute('start_month_1'));
	Start_Month_Min_Day =	Number(att_data.getAttribute('start_month_min_day'));
	End_Year =		Number(att_data.getAttribute('end_year'));
	End_Month_1 =		Number(att_data.getAttribute('end_month_1'));
	End_Month_Max_Day =	Number(att_data.getAttribute('end_month_max_day'));

//	Date_start = Start_Year*365 + sdays[Start_Month_1] + Start_Month_Min_Day - 1;
//	Date_end = End_Year*365 + sdays[End_Month_1] + End_Month_Max_Day - 1;

    $("resample").style.visibility = att_data.getAttribute('rs_visibility');
    $("var_name_top").innerHTML = att_data.getAttribute('var');
    $("var_name").innerHTML = att_data.getAttribute('var');
    $("ts_table").innerHTML = xmlDoc.getElementsByTagName('t_html')[0].childNodes[0].nodeValue;
    $("metadata").innerHTML = "<a href=\""+att_data.getAttribute('metadata')+"\" target=\"_blank\">Metadata link for<br /><b>"+att_data.getAttribute('var')+"</b></a>";
    if (lm) document.navigation.resample.selectedIndex = att_data.getAttribute('resample');
    if (lm) document.navigation.shade.selectedIndex = att_data.getAttribute('shade');

    load_map();
  });
}

/////////////////////////////////////////////////////////////////

function showLink(t) {
  var URL_div = $('url_link');

  if (URL_div.style.visibility == "visible") {
    URL_div.style.visibility = "hidden";
  }
  else {
    document.lnk.lnk.value = ((t) ?
	'http://'+document.domain+'/cgi-bin/map.pl' :
	document.URL.substr(0,(document.URL.indexOf('?')!=-1)?document.URL.indexOf('?'):document.URL.length)) +
	m_url_history[m_history][1].substr(m_url_history[m_history][1].indexOf('?'));

    URL_div.style.left = Number(Map_coord[0]+Map_size[0]-URL_div.offsetWidth).toString() +"px";
    URL_div.style.top  = Number(Map_coord[1]+Map_size[1]-URL_div.offsetHeight).toString()+"px";
    URL_div.style.visibility = "visible";
    document.lnk.lnk.focus();
    document.lnk.lnk.select();
  }
}

function printMap() {
  var src  = img_0.src;
  var link = "about:blank";

  // We break the closing script tag in half to prevent
  // the HTML parser from seeing it as a part of
  // the *main* page.
  var html = "<html>\n" +
    "<head>\n" +
    "<title>Temporary Printing Window</title>\n" +
    "<script>\n" +
    "function step1() {\n" +
    "  setTimeout('step2()', 10);\n" +
    "}\n" +
    "function step2() {\n" +
    "  window.print();\n" +
    "  window.close();\n" +
    "}\n" +
    "</scr" + "ipt>\n" +
    "</head>\n" +
    "<body onLoad='step1()'>\n" +
    "<img src='" + src + "'/>\n" +
    "</body>\n" +
    "</html>\n";
  var pw = window.open(link, "_new");

  pw.document.open();
  pw.document.write(html);
  pw.document.close();
}

/////////////////////////////////////////////////////////////////
/*
*
*	Page History Block
*
*/
/////////////////////////////////////////////////////////////////

var m_url_history = new Array;
var m_history = -1;

function map_history(page) {
  if (page==-1 && !m_history) return false;
  if (page== 1 &&  m_history==(m_url_history.length-1)) return false;

  if (Loading) return false;
  map_loading();

  m_history = Math.max(m_history+page,0);
  m_history = Math.min(m_history,m_url_history.length-1);

	///////////////////////////
	///	Restore Page	///
	///////////////////////////

  Type = m_url_history[m_history][0];

  img_0.src	= m_url_history[m_history][1];
  img_1.src	= m_url_history[m_history][2];
  ref_map_src	= m_url_history[m_history][2];

  mapExtent.setExtent(
	[m_url_history[m_history][3],m_url_history[m_history][4],m_url_history[m_history][5],m_url_history[m_history][6]]
  );

  Ts 			= m_url_history[m_history][7];
  Start_Year		= m_url_history[m_history][8];
  Start_Month_1		= m_url_history[m_history][9];
  Start_Month_Min_Day	= m_url_history[m_history][10];
  End_Year		= m_url_history[m_history][11];
  End_Month_1		= m_url_history[m_history][12];
  End_Month_Max_Day	= m_url_history[m_history][13];

  $("resample").style.visibility		= m_url_history[m_history][14];
  $("var_name_top").innerHTML			= m_url_history[m_history][15];
  $("var_name").innerHTML			= m_url_history[m_history][16];
  $("ts_table").innerHTML			= m_url_history[m_history][17];
  $("metadata").innerHTML			= m_url_history[m_history][18];
  document.navigation.resample.selectedIndex	= m_url_history[m_history][19];
  document.navigation.shade.selectedIndex	= m_url_history[m_history][20];
  if (document.date && document.date.year)
	document.date.year.selectedIndex	= m_url_history[m_history][21];
  if (document.date && document.date.month)
	document.date.month.selectedIndex	= m_url_history[m_history][22];
  if (document.date && document.date.day)
	document.date.day.selectedIndex		= m_url_history[m_history][23];
}

/////////////////////////////////////////////////////////////////

function push_history() {
  m_url_history.push([
	Type,
	img_0.src,ref_map_src,
	mapExtent.extent[0],mapExtent.extent[1],mapExtent.extent[2],mapExtent.extent[3],
	Ts,Start_Year,Start_Month_1,Start_Month_Min_Day,End_Year,End_Month_1,End_Month_Max_Day,
	$("resample").style.visibility,
	$("var_name_top").innerHTML,
	$("var_name").innerHTML,
	$("ts_table").innerHTML,
	$("metadata").innerHTML,
	document.navigation.resample.selectedIndex,
	document.navigation.shade.selectedIndex,
	(document.date && document.date.year)  ? document.date.year.selectedIndex  : 0,
	(document.date && document.date.month) ? document.date.month.selectedIndex : 0,
	(document.date && document.date.day)   ? document.date.day.selectedIndex   : 0
  ]);
}

/////////////////////////////////////////////////////////////////
/*
*
*	Data Download Block
*
*/
/////////////////////////////////////////////////////////////////

function Load_Data(dObj,checkBox) {
  if (checkBox.checked == false) {
    checkBox.checked = true;
    return false;
  }
  else if (Loading) {
    checkBox.checked = false;
    return false;
  }
  else { Loading = true; }

  dObj.checkBox = checkBox;
  dObj.load(img_0.src.replace(Map_script,XML_script).replace(/&towns=.+/,"")+"&data_dims=320_240");
}

//////////////////////////////////////////////////////////////////
///////////////////////   Map Extent Object   ////////////////////

function extentObj(full_extent,map_size) {
  if (Math.abs((full_extent[2]-full_extent[0])/(full_extent[3]-full_extent[1]) - map_size[0]/map_size[1]) > 0.001) alert ("Missmatch in map extent and map size proportions...");

  this.full_extent = full_extent;	/// Reference to map coords array [xmin,ymin,xmax,ymax]
  this.cols = map_size[0];		/// Map img width
  this.rows = map_size[1];		/// Map img height
  this.extent = full_extent.slice(0);	/// Current map extent
  this.px_scale = (full_extent[2]-full_extent[0])/map_size[0];
}

extentObj.prototype.setSize = function(width,height) {
  this.cols = width;
  this.rows = height;
  this.px_scale = (this.extent[2]-this.extent[0])/width;
};

extentObj.prototype.setExtent = function(new_extent) {
  if (Math.abs((new_extent[2]-new_extent[0])/(new_extent[3]-new_extent[1]) - this.cols/this.rows) > 0.001 && !confirm("Missmatch in map extent and map size proportions.\nDo you want to use wrong extents?")) return false;

  this.extent = new_extent.slice(0);		// makes copy
  this.px_scale = (this.extent[2]-this.extent[0])/this.cols;
};

extentObj.prototype.makeExtent = function(center_X,center_Y,zoom) {
  var Map_span = new Array(this.extent[2]-this.extent[0],this.extent[3]-this.extent[1]);

  Map_span[0] /= zoom; Map_span[1] /= zoom;

  if (Map_span[0] >= this.full_extent[2]-this.full_extent[0])
  {
    this.extent = this.full_extent.slice(0);	// makes copy
  }
  else
  {
    var c_lon = this.extent[0]+center_X*this.px_scale;
    var c_lat = this.extent[3]-center_Y*this.px_scale;

    if ((c_lon-Map_span[0]/2)<this.full_extent[0]) c_lon = this.full_extent[0] + Map_span[0]/2;
    if ((c_lon+Map_span[0]/2)>this.full_extent[2]) c_lon = this.full_extent[2] - Map_span[0]/2;
    if ((c_lat-Map_span[1]/2)<this.full_extent[1]) c_lat = this.full_extent[1] + Map_span[1]/2;
    if ((c_lat+Map_span[1]/2)>this.full_extent[3]) c_lat = this.full_extent[3] - Map_span[1]/2;

    this.extent[0] = c_lon - Map_span[0]/2;
    this.extent[2] = c_lon + Map_span[0]/2;
    this.extent[1] = c_lat - Map_span[1]/2;
    this.extent[3] = c_lat + Map_span[1]/2;
  }

  this.px_scale = (this.extent[2]-this.extent[0])/this.cols;
};

extentObj.prototype.coords = function(x,y,round_factor) {
  var Lon = Math.floor((this.extent[0]+x*this.px_scale)*round_factor)/round_factor;
  var Lat = Math.floor((this.extent[3]-y*this.px_scale)*round_factor)/round_factor;
  Lon = (Lon<0?"&nbsp;":"&nbsp;&nbsp;") + Lon;
  Lat = (Lat<0?"&nbsp;":"&nbsp;&nbsp;") + Lat;

  return [Lon,Lat];
};

extentObj.prototype.to_String = function(sel) {
  var Str = this.extent[0]+"_"+this.extent[1]+"_"+this.extent[2]+"_"+this.extent[3];

  if (sel) Str = "&extent="+Str+"&size="+this.cols+"x"+this.rows;

  return Str;
};

//////////////////////////////////////////////////////////////////
///////////////////////   Data Object   //////////////////////////

function dataObj(target_name) {
  this.loaded = false;
  this.target = document.getElementById(target_name);
  this.checkBox = null;
  this.var_name = "&nbsp;";
  this.units = "&nbsp;";
  this.ncols = 0;
  this.nrows = 0;
  this.nodata= 0;
  this.data = new Array();
}

dataObj.prototype.load = function(url) {
  var dObj = this;
  dObj.target.innerHTML = "Loading...";
  DownloadUrl(url, true, function(xmlDoc,responseCode) {
    if (responseCode == 200) {
      var att_data = xmlDoc.getElementsByTagName('js_data')[0];
	dObj.units =        att_data.getAttribute('units');
	dObj.ncols = Number(att_data.getAttribute('ncols'));
	dObj.nrows = Number(att_data.getAttribute('nrows'));
	dObj.nodata= Number(att_data.getAttribute('nodata'));
//      var nodataReg = new RegExp(dObj.nodata,"g"); // replace(nodataReg,"No Data").

      var array = xmlDoc.getElementsByTagName('numbers')[0].firstChild.nodeValue.replace(/,,/g,",1,").split(",");

      for (var i=0; i<array.length/2; i++) {
	for (j=0; j<array[i*2+1]; j++) {
	  dObj.data.push(array[i*2]);
	}
      }
			// Populate Classes Legend
      if (xmlDoc.getElementsByTagName('legend')[0]) {
	var Pairs = xmlDoc.getElementsByTagName('legend')[0].firstChild.nodeValue.split(",");
	var Str_data = new Array();
	for (var k=0; k<Pairs.length/2; k++) {
	  Str_data[Number(Pairs[k*2])] = Pairs[k*2+1];
	}
	for (var k=0; k<dObj.data.length; k++) {
	  dObj.data[k] = (dObj.data[k]==dObj.nodata)?'No Data':Str_data[parseInt(dObj.data[k])];
	}
      }

      dObj.loaded = true;
      dObj.target.innerHTML = "&nbsp;";
    }
    else { dObj.target.innerHTML = "Failed to Load..."; }

    Loading = false;
  });
};

dataObj.prototype.clear = function() {
  this.loaded = false;
  this.target.innerHTML = "Check to Load";
  if (this.checkBox) this.checkBox.checked = false;
  this.data = new Array();
};

//////////////////////////////////////////////////////////////////
/*
*
*	XML Block
*
*/
///////////////////////////////////////////////////////////////////////

function DownloadUrl(url,xml,func) {
  var req,responseData,responseCode;

  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
	req = new XMLHttpRequest();
  // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
	req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else {
    alert("This browser does not support AJAX -\nAsynchronous JavaScript and XML...");
    return false;
  }

  if (req) {
	req.open("GET", url, true);
	req.onreadystatechange = function() {
	  if (req.readyState == 4) {
	    responseCode = req.status;
		// only if "OK"
	    if (responseCode == 200) {
		responseData = xml ? req.responseXML : req.responseText;
	    }
	    else { alert("There was a problem retrieving the XML data:\n" + req.statusText); }

	    func(responseData,responseCode);
	  }
	}
	req.send(null);
  }
  else {
    alert("This browser does not support AJAX -\nAsynchronous JavaScript and XML...");
    return false;
  }
}

/////////////////////////////////////////////////////////////////

function loadXMLstring(text) {
  // code for IE
  if (window.ActiveXObject)
  {
	var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async="false";
	xmlDoc.loadXML(text);
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (window.DOMParser)
  {
	var parser=new DOMParser();
	var xmlDoc=parser.parseFromString(text,"text/xml");
  }
  else {
    alert("This browser does not support XML...");
    return false;
  }
  return xmlDoc;
}

//////////////////////////////////////////////////////////////////
/*
*
*	Helper functions
*
*/
///////////////////////////////////////////////////////////////////////

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

/////////////////////////////////////////////////////////////////

function parseArgs(url) {
  var Args = new Array();
  var argString = (url.indexOf('?')!=-1)?url.substr(url.indexOf('?')+1):'';
  while (argString) {
    var midPos = argString.indexOf('=');
    if (midPos != -1) {
      var len = (argString.indexOf('&')!=-1) ? argString.indexOf('&') : argString.length;
      var key = argString.substr(0,midPos);
      var val = argString.substr(midPos+1,len-midPos-1);
      Args[key] = val;
      argString = argString.substr(len+1);
    }
    else {argString = '';}
  }
  return Args;
}

// -->
